I was solving the 3rd problem at Project Euler which requires me to calculate the largest prime factor of 600851475143 which I think is a really large number (more than 6 billion).
QB64
At first, I tried solving this problem using QB64
.
CLS
n = 600851475143
FOR x = 1 TO n
IF n MOD x = 0 THEN
FOR y = 1 TO (x / 2) - 1
IF x MOD y = 0 THEN
factor = y
END IF
NEXT y
IF factor = 1 THEN
ans = x
END IF
END IF
NEXT x
PRINT ans
However, on running the program, QB64
would appear busy executing the program, but no result would appear even after waiting for a long time.
QuickBasic 4.5
On getting no help from a compiler, I switched to QuickBasic 4.5
which is an interpreter. I executed the same code, but on trying to run the program, QuickBasic
would trigger the following error on the line where I define the number.
Overflow
And, the program wouldn't execute at all.
Repl.it / QBasic
Getting no success, I tried using an online interpreter. View the live code at repl.it
On executing the same code on repl.it
, the results were similar to what I got for QB64
PHP
I termed this as a limitation for the QBasic
language and hence re-wrote the same logic in PHP
.
$n = 600851475143;
for($x = 1; $x <= $n; $x++){
if($n % $x == 0){
for($y = 1; $y < $x/2; $y++){
if($x % $y == 0){
$factor = $y;
}
}
if($factor == 1){
$ans = $x;
}
}
}
echo $ans;
Localhost
On executing this code in my local server (http://localhost:8000
) I got no result, instead, the following error:
Maximum execution time of 30 seconds exceeded -- at line 5
I increased the max_execution_time
from the php.ini
to a few hours. However, I got now result from the code as it never executed completely. I waited for more than 6 hours, but the code continued to execute indefinitely without giving any result.
Online PHP compilers
I then tried a number of online compilers like:
However, none of them could give me the result as they would either never stop executing or would show the maximum execution time error.
So, my question is, How can I SUCCESSFULLY execute this code to solve my problem? Do I need to:
- Use a different, more efficient Compiler / Interpreter
- Switch to a different language altogether
- Make my logic even more concise to reduce execution time
Note: When I used the above codes with a smaller number like 13195
, the result was exactly correct, i.e., 29
.