用python编写函数,完成因式分解.例如10 = 2*5,60=2*2*3*5
时间: 2024-01-17 11:17:31 浏览: 41
以下是Python实现因式分解的函数及其示例代码:
```python
def factorization(n):
factors = []
i = 2
while i <= n:
if n % i == 0:
factors.append(i)
n = n / i
else:
i += 1
return factors
# 示例代码
print(factorization(10)) # 输出:[2, 5]
print(factorization(60)) # 输出:[2, 2, 3, 5]
```
相关问题
利用python编写程序,用户输入一个合数,将其分解为质因式输出,如:60=2*2*3*5,每个因子都是质数,质数判断过程在一个自定义函数内完成。
可以使用以下代码实现:
```python
def is_prime(num):
"""判断一个数是否为质数"""
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def prime_factorization(num):
"""将一个合数分解为质因数"""
factors = []
for i in range(2, num + 1):
if num % i == 0 and is_prime(i):
factors.append(i)
num //= i
if num == 1:
break
return factors
num = int(input("请输入一个合数:"))
factors = prime_factorization(num)
print("{}=".format(num), end="")
for i in range(len(factors)):
if i == len(factors) - 1:
print(factors[i])
else:
print("{}*".format(factors[i]), end="")
```
运行程序,输入一个合数,程序会输出其质因数分解结果。例如,输入60,输出为:
```
请输入一个合数:60
60=2*2*3*5
```
用python编写程序,主要利用函数知识和简单语句,用户输入一个合数,将其分解为质因式输出,如:60=2*2*3*5,每个因子都是质数,质数判断过程在一个自定义函数内完成。
好的,下面是代码实现:
```python
def is_prime(num):
"""
判断一个数是否为质数
"""
if num <= 1:
return False
for i in range(2, int(num**0.5)+1):
if num % i == 0:
return False
return True
def prime_factorization(num):
"""
将一个合数分解成质因数
"""
result = []
for i in range(2, num+1):
if is_prime(i) and num % i == 0:
result.append(i)
num //= i
if num == 1:
break
return result
num = int(input("请输入一个合数:"))
result = prime_factorization(num)
print("{}=".format(num), end='')
for factor in result:
print("{}{}".format(factor, "*" if result.index(factor) != len(result)-1 else ""), end='')
```
运行程序,输入一个合数,如60,输出结果为:60=2*2*3*5。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)