文章目录
C
/* 分解质因数(本解答利用迭代减小规模的思路)问题E:质因数分解(综合)[中]
题目描述
输入一个正整数,将它分解为质因数(质数即素数)。例如,
输入90,
输出90=2*3*3*5
90输出
90=2*3*3*5
样例输入
20样例输出
20-2*2*5 */
/* 分解质因数(本解答利用迭代减小规模的思路) */
int isprime(int n);
int main() {
int n;
while (scanf("%d", &n) != EOF)
{
printf("%d=", n);
//迭代减小n的规模.
for (int i = 2; i < n + 1;)
{
if (n != 1 && n % i == 0 && isprime(i))
/*n!=1:还未分解完毕;n%i=0:n被i整除;isprime(i):i是质数.*/
{
printf("%d", i);/*打印该因子*/
n = n / i;//不是%;n=1的时候分解完毕.
if (n != 1) printf("*");/*如果当前因子i不是最后一个因子,打印乘号*/
}
else
{
i++;
}
}//for
printf("\n");
}
return 0;
}
int isprime(int n)
{
if (n == 2) return 1;
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
python版
def isprime(n):
if n==1 or n==0:
return False
for i in range(2,n):
if n%i==0:
return False
return n
def decompose():
n=(int)(input("input a positive integer:"))
list_factor=[]
list_power=[]
list=[list_factor,list_power]
""" python3:the dict is ordered! """
# dict={}
""" use the index variable to guide the power update operation """
j=-1
i=2
# while structure is more fit for the judge than for in structure:
while n>1:
if n%i==0:
if isprime(i):
""" iterate n: """
n=n//i
""" update the prime factor and its correspondent power """
if(i not in list_factor):
list_factor.append(i)
list_power.append(1)
j+=1
else:
list_power[j]+=1
else:
i+=1
else:
i+=1
return list
print(decompose())