pythonfor-loopfactorization

Factorization: What went wrong with d?


Consider:

Enter image description here

Input: 20
       17
       999997

Output: 2^2 * 5
        17
        757 * 1321

My code:

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)

I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is

if i input 12, it outputs 2 2

Enter link description here


Solution

  • 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
    

    You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).

    As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)