Python程序查找数字的质因数

编写一个Python程序,使用For循环和While循环查找数字的质因数,并附带示例。

Python程序使用For循环查找数字的质因数

此Python程序允许用户输入任何正整数。接下来,下面的代码将使用For循环返回该数字的质因数。

提示:我建议您参考查找数字的因数质数文章,以理解此Python程序的逻辑。

 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))
Program to find Prime Factors of a Number

使用While循环查找数字的质因数

此数字质因数程序与上述程序相同。在此Python示例中,我们将For循环替换为While循环

 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

数字的质因数输出。

 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