用 For 循环和 While 循环编写一个 Python示例来寻找一个数的质因数,并给出一个例子。
这个 python 程序允许用户输入任何正整数。接下来,Python 使用 For 循环返回该数的质因数。
提示:建议大家参考一个数的因数、质数的文章来理解这个 python 程序的逻辑。
# Python Program to find Prime Factors of a Number
Number = int(input(" Please Enter any Number: "))
for i in range(2, Number + 1):
if(Number % i == 0):
isprime = 1
for j in range(2, (i //2 + 1)):
if(i % j == 0):
isprime = 0
break
if (isprime == 1):
print(" %d is a Prime Factor of a Given Number %d" %(i, Number))
这个 Python 质数因数程序和上面的一样。在本 Python 示例中,我们将 For Loop 替换为 While Loop
# Python Program to find Prime Factors of a Number
Number = int(input(" Please Enter any Number: "))
i = 1
while(i <= Number):
count = 0
if(Number % i == 0):
j = 1
while(j <= i):
if(i % j == 0):
count = count + 1
j = j + 1
if (count == 2):
print(" %d is a Prime Factor of a Given Number %d" %(i, Number))
i = i + 1
Python 一个数的质因数输出
Please Enter any Number: 250
2 is a Prime Factor of a Given Number 250
5 is a Prime Factor of a Given Number 250
标签: seo