You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.4 KiB
50 lines
1.4 KiB
#include <stdio.h>
|
|
#include "utils.h"
|
|
|
|
/*
|
|
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.
|
|
|
|
|
|
https://projecteuler.net/problem=14
|
|
*/
|
|
|
|
int main(int argc,char**argv) {
|
|
int maxChain=0;
|
|
long maxNumb=0;
|
|
int counter=1;
|
|
while (counter<1000000) {
|
|
//printf("Calculating %d...\n",counter);
|
|
long numb=counter;
|
|
int chainCount=0;
|
|
while (numb!=1) {
|
|
if (numb%2==0) {
|
|
numb/=2;
|
|
} else {
|
|
numb=3*numb+1;
|
|
}
|
|
chainCount++;
|
|
//printf("%d>",numb);
|
|
}
|
|
if (chainCount>maxChain) {
|
|
maxChain=chainCount;
|
|
maxNumb=counter;
|
|
printf("Max chain is now %d (%d)...\n",maxChain,maxNumb);
|
|
}
|
|
counter++;
|
|
}
|
|
printf("\n\nMax chain count is %d for number %d\n",maxChain,maxNumb);
|
|
|
|
return 0;
|
|
} |