用 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
原創文章,作者:C4A03,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126372.html