-3

So my program is supposed to find the prime factors of an integer and then the contents of the integer array is printed out and the values in the array are supposed to be multiplied together (giving you the original number) this is what it is supposed to look like

Prime Factorization Program

Enter an integer > 1: 210 

Prime Factors 
2
3
5
7
Check Product = 210

this is my code and my results

def main():
    a = [0]*20
    print("Prime Factorization Program")
    print()
    num = eval(input("Enter an integer > 1: "))
    count = 0
    for k in range(1,num):
        if num % k == 0:
            a[count]= k
            count = count + 1

    mySum = 0
    for k in range(count):
        mySum = mySum + a[k]
    print()
    print("Prime Factors")
    for k in range(count):
        print(a[k])
    print("Check Product =",mySum)

main()

here are my result

Prime Factorization Program

Enter an integer > 1: 210

Prime Factors
1
2
3
5
6
7
10
14
15
21
30
35
42
70
105
Check Product = 366
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

1
  1. Problem - If f is a factor, you don't want to count multiples of f.
    Solution - Once you identify a factor f, divide n by f.
    Example - 210 is divisible by 2; divide by 2 and thereafter process 105. That ensures you don't count any more multiples of 2 like 6 or 10. 105 is divisible by 3; divide by 3 and continue with 35.

  2. Problem - Prime factors can show up multiple times. 12 = 2×2×3.
    Solution - If f is a factor, keep checking for it and dividing by f until you've accounted for all occurrences.
    Example - 12 is divisible by 2; divide by 2 to get 6. 6 is still divisible by 2; divide by 2 again to get 3. 3 is not divisible by 2; continue to the next factor.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Because your code is printing all the factor instead of just prime factors. Below is the sample function you may refer for prime factorization:

def prime_factors(n):
    prim_facs = []
    d = 2
    while d*d <= n:
        while (n % d) == 0:
            prim_facs.append(d)
            n //= d
        d += 1
    if n > 1:
       prim_facs.append(n)
    return prim_facs

# Sample Example
# >>> prime_factors(210)
# [2, 3, 5, 7]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126