-4

I need help to solve Project Euler problem 3 with list.append(). If I put print like above it's going forever. How can I read the entire list?

# What is the largest prime factor of the number 600851475143?
list =[0]
for i in range(2,600851475143):
    if(600851475143%i==0):
        list.append(i)
    print(list)
VintageMind
  • 65
  • 2
  • 9
mesut.a
  • 15
  • 5
  • 1
    Check out [What is the most efficient way of finding all the factors of a number in Python?](https://stackoverflow.com/q/6800193/3890632) – khelwood Aug 29 '21 at 22:41
  • don't print the all found factors inside for loop as this will print for 600851475142 times and having all found no so far. you can print once you have found all the factors. in this case after for loop completion. then you can move to find the maximum prime factor – sahasrara62 Aug 29 '21 at 22:46
  • 2
    "Where I have to put print?" Well, you tell me. How many times do you want `print` to happen? How many times does code happen that's inside the loop? How many times does code happen that's outside the loop? Therefore, where does the `print` go? – Karl Knechtel Aug 29 '21 at 22:52
  • Separately: you probably have noticed from your output that `600851475143` is divisible by `71`. Can you think of a way to use this information to reduce the workload? Does it tell you something about how high of a number you have to test in order to find the remaining factors? Also, even before you started dividing, can you think of a number smaller than `600851475143` that is an upper limit on how big the factors could be? (Hint: is the result of `8053 / 97` larger or smaller than `97`?) – Karl Knechtel Aug 29 '21 at 22:55

2 Answers2

0

Either inside the if statement, or after the loop. Inside the if statement will print every time a factor is found:

list =[0]
for i in range(2,600851475143):
    if(600851475143%i==0):
        list.append(i)
        print(list)

After the loop will print once, after the loop completes:

list =[0]
for i in range(2,600851475143):
    if(600851475143%i==0):
        list.append(i)
print(list)
pelmetennui
  • 136
  • 1
  • 3
0

So for your particular problem, you would put the print function outside the for loop because you just want to print the final product which is the largest prime factor of the number 600851475143. And in your code you're appending to the list which again means you should put the print function outside the for loop like below:

    list =[0]
    for i in range(2,600851475143):
       if(600851475143%i==0):
         list.append(i)
    print(list)

If you put it inside, you would be printing "i" each time it is getting looped and added to the list and you don't want that:

    list =[0]
    for i in range(2,600851475143):
       if(600851475143%i==0):
         list.append(i)
         print(list)
Nimantha
  • 6,405
  • 6
  • 28
  • 69
VintageMind
  • 65
  • 2
  • 9