(Problem 14)Longest Collatz sequence
来源:互联网 发布:linux常用命令查看IP 编辑:程序博客网 时间:2024/05/17 07:48
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.
方法1:
#include<stdio.h>#include<math.h>#include<string.h>#include<ctype.h>#include<stdlib.h>#include<stdbool.h>int powcount(long long n) //计算2的幂数{int count=0;while(n>>=1) count++;return count;}bool ispower(long long v) //判断n是否为2的幂{if(((v & (v - 1)) == 0)) return true;else return false;}int length(long long n){int sum=1;while(1){if(n==1) break;if((n & 1)==0){if(ispower(n)) return sum+powcount(n);else n=n/2;}else n=3*n+1;sum++;}return sum;}int main(){int i,t,k,max=0;for(i=2; i<1000000; i++){t=length(i);if(t>max){max=t;k=i;}}printf("%lld\n",k);return 0;}
方法2:
#include<stdio.h>#include<math.h>#include<string.h>#include<ctype.h>#include<stdlib.h>#include<stdbool.h>int a[1000001];void find(){long long i,j,k,f,sum,max=0;a[1]=1,a[2]=2;for(j=3; j<1000000; j++){sum=1,k=i=j;while(1){if((i & 1)==0){i=i/2;if(i<k){a[k]=sum+a[i];break;}}else{i=3*i+1;}sum++;}if(a[k]>max){max=a[k];f=k;}}printf("%d\n",f);}int main(){find();return 0;}
Answer:
837799- (Problem 14)Longest Collatz sequence
- Problem 14 Longest Collatz sequence(暴力)
- Problem 14:Longest Collatz sequence
- Problem 14:Longest Collatz sequence
- projecteuler---->problem=14----Longest Collatz sequence
- Project Euler: Problem 14 Longest Collatz sequence
- Project Euler Problem 14 Longest Collatz sequence
- PE 14 Longest Collatz sequence
- 欧拉计划(14)Longest Collatz sequence
- 14 Longest Collatz sequence - Project Euler
- project euler 14 Longest Collatz sequence
- Longest Collatz sequence
- Longest Collatz sequence
- 欧拉项目第14题 Longest Collatz sequence
- Project Euler 014 Longest Collatz sequence
- Problem 14 of Collatz Problem
- UVa 694 The Collatz Sequence(序列)
- UVA - 694 The Collatz Sequence(水题)
- 代理
- VS2010中使用Jquery调用Wcf服务读取数据库记录
- 进程与线程的区别?
- android之service使用
- Ubuntu12.10编译Android 4.0.3的常见错误
- (Problem 14)Longest Collatz sequence
- 连续使用 glRotate () 旋转
- uva167 The Sultan's Successors
- POJ 1195 Mobile phones(二维树状数组)
- 计算机总线
- Wormholes
- 一个solution下放两个工程,以及main 的问题
- 用WebORB实现flex + .net后台的Remoting
- 10387 - Billiard