[Project Euler] Problem 3

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

  
    
#include < iostream >
using namespace std;

int prime[] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 ,
43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ,
101 , 103 , 107 , 109 , 113 , 127 , 131 , 137 , 139 ,
149 , 151 , 157 , 163 , 167 , 173 , 179 , 181 , 191 ,
193 , 197 , 199 , 211 , 223 , 227 , 229 , 233 , 239 ,
241 , 251 , 257 , 263 , 269 , 271 , 277 , 281 , 283 ,
293 , 307 , 311 , 313 , 317 , 331 , 337 , 347 , 349 ,
353 , 359 , 367 , 373 , 379 , 383 , 389 , 397 , 401 ,
409 , 419 , 421 , 431 , 433 , 439 , 443 , 449 , 457 ,
461 , 463 , 467 , 479 , 487 , 491 , 499 , 503 , 509 ,
521 , 523 , 541 , 547 , 557 , 563 , 569 , 571 , 577 ,
587 , 593 , 599 , 601 , 607 , 613 , 617 , 619 , 631 ,
641 , 643 , 647 , 653 , 659 , 661 , 673 , 677 , 683 ,
691 , 701 , 709 , 719 , 727 , 733 , 739 , 743 , 751 ,
757 , 761 , 769 , 773 , 787 , 797 , 809 , 811 , 821 ,
823 , 827 , 829 , 839 , 853 , 857 , 859 , 863 , 877 ,
881 , 883 , 887 , 907 , 911 , 919 , 929 , 937 , 941 ,
947 , 953 , 967 , 971 , 977 , 983 , 991 , 997 };

bool isPrime( int n);

int main(){
long long num = 600851475143 ;

for ( int i = 799999 ; i > 1 ; i -= 2 ){
if (num % i == 0 && isPrime(i)){
cout
<< i << endl;
break ;
}
}
return 0 ;
}


bool isPrime( int n){
for ( int i = 0 ; i < 168 ; i ++ ){
if (n % prime[i] == 0 )
return false ;
}
return true ;
}

[Project Euler] Problem 3

好啦,得到的结果是正确的

但其实这个算法是错误的

在验证一个数是否是素数时,我们一般是从2到sqrt()

800000接近于600851475143的平方根

但实际上求解600851475143的最大质因数不应该认为该质因数小于sqrt(600851475143)

如15的最大质因数是5,但5不小于sqrt(15)

所以,改到下面的算法

  
    
#include < iostream >
using namespace std;

int main(){
long long num = 600851475143 ;
int divisor = 3 ;

while ( num > 1 ){
if ( num % divisor == 0 ){
num
/= divisor;
divisor
-= 2 ;
}
divisor
+= 2 ;
}
cout
<< divisor << endl;
return 0 ;
}

该算法思路更清晰

把因数从小到大一一分解出去,最后分解的因数必然是最大的因数

我们也可以把divisor声明为long long型的。

因为divisor可能超过了int的范围

你可能感兴趣的:(project)