HDU The 3n + 1 problem
来源:互联网 发布:淘宝客如何转成淘口令 编辑:程序博客网 时间:2024/04/30 03:46
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then n <- 3n + 1
5. else n <- n / 2
6. GOTO 2
Sample Input
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then n <- 3n + 1
5. else n <- n / 2
6. GOTO 2
Sample Input
1 10100 200201 210900 1000
Sample Output
1 10 20100 200 125201 210 89900 1000 174
递归求计算的次数,定义全局变量计数。
ps:这还并不是一个算法,因为你无法证明这个算法的有穷性,无法找出一个一定可以结束循环的数字,不能证明这个数字有还是没有。
这个题的坑就在于数字的大小(只用int是不够的)和输入输出。
输出的m,n 必须和输入的m,n相同,所以就必须定义max_num和min_num循环找出最大的cycle_num
C学的太浅,只能这么做了。
#include <stdio.h>#include <string.h>int val[1000000];long long int con = 0;long long int fun(long long int n){ if(n == 1){ con ++; return con; } else if(!(n % 2)){ n /= 2; con ++; fun(n); } else if(n % 2){ n = 3 * n + 1; con ++; fun(n); }}int main(void){ long long int m, n, j, max_num, min_num; memset(val,0, sizeof(val)); while(scanf("%lld%lld", &m, &n) != EOF){ long long int i, num = 0; long long int max = 0; if(m > n){ max_num = m; min_num = n; } else{ max_num = n; min_num = m; } for(i = min_num;i <= max_num; i++){ con = 0; if(val[i] != 0) num = val[i]; else{ num = fun(i); val[i] = num; } if(num > max) max = num; } printf("%lld %lld %lld\n", m, n, max); } return 0;}
0 0
- hdu 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- HDU 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- HDU 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- HDU 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- HDU 1032 The 3n + 1 problem
- hdu-1032-The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- HDU 1032 The 3n + 1 problem
- HDU 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- hdu 1032 The 3n + 1 problem
- HDU 1032 The 3n + 1 problem
- 设计模式之----策略模式
- 欢迎使用CSDN-markdown编辑器
- Java 中的自动类型转换
- JNI数据类型和签名(Signatures)
- 在Myeclipse中导入工程后会出现Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core
- HDU The 3n + 1 problem
- 图论 有向图的强连通分量(模板)LA 4287
- Android Studio快捷键
- 关于使用模板velicity或者其他工具生成word文档
- PLSQL 配置设置
- jquery $.ajax+php使用jsonp处理数据时,前端success :function无法获取服务器返回数据
- ECharts 3.0底层zrender 3.x源码分析1-总体架构
- QML跳转页面之后如何屏蔽上一个页面的按钮区域事件
- Linux free -m 详解命令