因式分解,请帮我看看d哪里出了问题,我是新手刚学

Factorization, Please help me see what went wrong with d, I’m a newbie just learning

enter image description here
input:20 17 999997 ouput: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)

我先求因数,再看是不是质数。有的话我看看是多少个素数

if i input 12 ,it output 2 2

enter link description here

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

你很接近。您忘记在循环的每次迭代开始时设置默认值,因此它们有时没有正确的值;并且您应该将 a 除以您找到的因子(i**s,因此 is 的幂),从而将其设置为不同的值。

如前所述,您的代码也遵循一种奇怪的编码风格。我建议您停止在每个语句之间放置换行符,并开始用空格分隔运算符(例如:range(3+5) 不好,range(3 + 5) 更具可读性)

我相信你需要的是下面的输出。

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 no:"))
i = 2
factors = []
while i<=a:
    if (a%i)==0:
        factors.append(i)
        a = a/i
    else:
        i = i+1
print(factors)

这里我返回的是一个列表,如果你需要你可以相应地改变类型。

这是inputs/outputs:

enter no:17
[17]
enter no:100
[2, 2, 5, 5]
enter no:12
[2, 2, 3]