Problem Statement
The following iterative sequence is defined for the set of positive integers:
n n/2 (n is even)
n 3n + 1 (n is odd)
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.
Solution
Idea 1 :(bruteforce)
#include <stdio.h> //Time : 0.833 S #define sz 1000000 #define LL __int64 #define UL unsigned long int main(){ int i,j,k,l; UL tmp,cnt,max,ans; max = 0; for(i = sz; i > 1; i--){ tmp = i; cnt = 0; while(tmp != 1){ if( tmp & 1) tmp = 3*tmp + 1; else tmp >>= 1; cnt++; } if(cnt > max){ max = cnt; ans = i; } } printf("%lu %lu\n",ans,max); return 0; }Idea 2: (Dynamic Programming)
#include <stdio.h> //Time : 0.073 S #define sz 1000000 #define LL __int64 #define UL unsigned long UL tb[sz+1]; UL calc(UL n){ if( n == 1) return 0; if(n < sz && tb[n]) return tb[n]; if(n & 1){ if( n < sz) return tb[n] = 1 + calc( n + (n << 1) + 1); else return 1 + calc( n + (n << 1) + 1); } if( n < sz) return tb[n] = 1 + calc( n >> 1); return 1 + calc( n >> 1); } int main(){ int i,j,k,l; UL tmp,cnt,max,ans; max = 0; for(i = sz; i > 1; i--){ cnt = calc(i); if(cnt > max){ max = cnt; ans = i; } } printf("%lu %lu\n",ans,max); return 0; }
No comments:
Post a Comment