Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eulers problem №3, code stucks on big numbers

Tags:

python

I'm currently learning Python, and practice with euler's problem's. I'm stuck on 3rd problem, my code didn't working on the big numbers, but with other number's it's working.

n = 600851475143 
x = 0
for i in range(2,n):
    if(n%i == 0):
        if(x < i): x = i
print(x)

The console just didn't get any results and stucks. P.S https://projecteuler.net/problem=3

(sorry for my bad english)

like image 824
Михаил Зубов Avatar asked Dec 02 '25 04:12

Михаил Зубов


2 Answers

It's running, but just the time it takes is huge. You can check by the following code, it keeps going to print x's.

n = 600851475143
x = 0
for i in range(2, n):
    if n % i == 0:
        if x < i:
            x = i
            print(x)

To save time, you can try the following code instead of your code:

n = 600851475143
x = 0
for i in range(2, n):
    if n % i == 0:
        x = n // i
        break
print(x) 

which prints 8462696833 instantly. But as @seesharper stated on the comment, it is merely the largest factor and not a prime factor. So it is not the correct answer to the Project Euler Problem #3.

like image 131
Gorisanson Avatar answered Dec 04 '25 19:12

Gorisanson


Check this code you will save a lot of time

Using sqrt for optimization

from math import sqrt
def Euler3(n):
    x=int(sqrt(n))
    for i in range(2,x+1):
        while n % i == 0:
            n //= i
            if n == 1 or n == i:
                return i
    return n
n = int(input())
print(Euler3(n))

Also, check my Euler git repo

There are only 6 solutions in python2 and it's pretty old but they are very well optimized.

like image 32
7u5h4r Avatar answered Dec 04 '25 19:12

7u5h4r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!