Sunday, 17 August 2014

Project Euler Problem 14.The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain?

main()
{
long long int k=1000000;
int n=1;
int large=1;
long long int p;
while(k>=1){
p=k;
while(p!=1)
{
if(p%2!=0){p=3*p+1;n++;}
else{if(p%2==0){p/=2;n++;}}
}
if(n>large){large=n;}
n=1;
k--;
}
k=1000000;
while(k>=13){
p=k;
while(p!=1)
{
if(p%2!=0){p=3*p+1;n++;}
else{if(p%2==0){p/=2;n++;}}
if(n==large){printf("%d\n",k);break;}
}
n=1;
k--;
}
}

No comments:

Post a Comment