-2

Hi I wrote this program in response to the following question:

"What is the largest prime factor of the number 600851475143?"

The program works for "composite" equal to 13195, but it does not work if I set it equal to 600851475143.

Why does this happen?

composite = 600851475143
for m in range (2,composite):
    while composite % m == 0:
        if composite / m == 1:
            break
        else:
            composite = composite / m
print(composite)
11
  • 6
    Please elaborate on "does not work". Commented Jun 18, 2018 at 21:47
  • 3
    What flavor of python do you use? Your code will not do what you expect it to do in Python 3. Commented Jun 18, 2018 at 21:48
  • 1
    You've got a 600-billion-iteration outer loop. That's not going to finish quickly. Commented Jun 18, 2018 at 21:52
  • Sorry. When I say it doesn't work I mean to say that nothing happens. The program doesn't run for a sufficiently large value of "composite." Commented Jun 18, 2018 at 21:52
  • Possible duplicate of Python Finding Prime Factors Commented Jun 18, 2018 at 21:52

1 Answer 1

2

The issue is the combination this line:

for m in range (2,composite):

and this line:

    composite = composite / m

Range won't recalculate while you are looping. See this question for more details: Changing the number of iterations in a for loop

Instead, your code should be the following (to fix that issue):

composite = 600851475143

m = 2
while m < composite:
    while composite % m == 0:
        print(composite, m)
        if composite / m == 1:
            break
        else:
            composite = composite / m
    m += 1
~                
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.