考虑:
在此处输入图像描述
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
我的代码:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
我会先找到因子,然后看看它是否是质数。如果是这样,我会看看它有多少个质数
如果我输入12,它输出2 2
在此处输入链接说明
我相信你需要下面的输出。
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
这将给出给定数字的素因子。正如我所理解的,这正是你想要的。
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
你很接近了。你忘了在每次循环迭代的开始设置默认值,所以它们有时没有正确的值;您应该将< code>a设置为不同的值,方法是用它除以您找到的因子(< code>i**s,因此< code>i是< code>s的幂)。
如前所述,您的代码也遵循一种奇怪的编码风格。我建议你停止在每个语句之间放置换行符,并开始用空格分隔运算符(例如:range(3 5)不好,range(3 5
)更具可读性)
你在这里使用了太多的循环,这就是为什么你会变得太困惑。这是用于相同目的的代码(如果我正确理解您的问题)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
这里我返回一个列表,如果你愿意,你可以相应地更改类型。
以下是输入/输出:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]