不用别人认可也不用别人理解,尽情去做自己认为应该做的事……

2009年5月6日星期三

Problem 14--(c)

Problem 14
05 April 2002

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?

NOTE: Once the chain starts the terms are allowed to go above one million.

Answer:
837799
code:
#include
int main(void)
{
long int num,max=0,i,j,answer;
for(i=2;i<1000000;i++)
{
j=i;
num=0;
while(j!=1)
{
if(j%2==0) {j=j/2;num++;}
else {j=3*j+1;num++;}
}
if(num>max) {max=num;answer=i;}
}
printf("%ld\n",answer);
return 0;
}

0 评论: