Tuesday, May 1, 2012

Project Euler, Problem 3 solution

Problem 3

Well...

Cheat One

Cheat Two

Cheat Three

I'm sure there is a lot of other cheats in Internet.

 

JavaScript (SpiderMonkey):

var num = 600851475143;
var ans = 0;
for(var div = 3; ; div += 2) {
    if(!(num % div)) {
        do {num /= div;} while (!(num % div));
        if(num == 1) {
            ans = div;
            break;
        }
    }
}
print(ans);

(time: 0.02s memory: 4984 kB)

Congratulations, the answer you gave to problem 3 is correct.
You are the 127054th person to have solved this problem.

UPDATED at 16 May 2012: Solution with one loop:

var num = 600851475143;
var div = 2;
while (num > 1) {
    if (0 == (num % div)) {
        num /= div;
        div--;
    }
    div++;
}
print(div);

(time: 0.02s memory: 4984 kB)

No comments:

Post a Comment