#include <iostream>
using namespace std;
int prim( long long x ) {
int s = 0;
for( long long i = 1; i <= x ; i++ ) {
if( x % i == 0 ) {
s++;
}
}
if( s == 2 ) {
return 1;
}
return 0;
}
int main() {
long long A = 600851475143;
long long i = 2;
long long C = 0;
while( i < (A/2) ) {
while( A % i == 0 ) {
A = A / i;
if( i > C ) {
C = i;
}
}
i++;
}
if( prim(C) ) {
cout<<C;
}
return 0;
}
This is the code I made for Project Euler problem 3. I don't understand why when I run it, it gives me 1471. It's a good answer but not the biggest. But if I change i = 1471
it gives me the correct answer 6857 ... Where is the problem? Why doesn't it "automagically" give me the good 6857 answer but 1471 when I start from 2?
PS. I know I don't have to use long long
everywhere.
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
open Project Euler site and signup (if you haven't already) using your credentials.it is completely free. In order to solve the problems,signin and go to Archived Problems - Project Euler .
My answer is yes. Project Euler problems are very good and you need a sharp programming mind to solve them. Project Euler includes couple of number theory problems which are very interesting and need strong logic to code.
Projecteuler-solutions provides merely a list of answers -- that is, it does not provide solutions or code for individual problems.
Your factorization algorithm needs to pick between C
and A
, because at the end of the process A
contains the remainder, which is also a factor of the original A
. If it happens to be the largest one, your code would miss it.
if (A > C) {
C = A;
}
Once you make this modification, your code produces the correct answer (demo).
Note: now that your program is running, you may consider a few modifications:
A/2
is inefficient; you can stop at the square root (do you see why?)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With