UVA - 694 The Collatz Sequence

来源:互联网 发布:淘宝好吃的点心店铺 编辑:程序博客网 时间:2024/05/20 11:35

题目大意:给出数字 A 和范围 L,在范围 L 内运算,当 A 为偶数 A = A/2,当 A 为奇数 A = 3×A+1,当 A = 1 时停止。问运算次数。

解题思路:简单模拟。运算过程中可能会超出 int 范围所以用 long long,溢出提示是 TLE 还以为算法有问题,结果想多了,一把心酸泪。

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<algorithm>using namespace std;int cnt;int tot = 0;int main() {    int A, L;    while (scanf("%d%d", &A, &L)!= EOF && A != -1 && L != -1) {        long long n = A; cnt = 1;        while (n != 1 && n <= L) {            if (n%2) n = 3*n+1;            else if (!(n%2)) n /= 2;            cnt++;        }        if (n != 1) cnt--;        printf("Case %d: A = %d, limit = %d, number of terms = %d\n", ++tot, A, L, cnt);    }return 0;}
0 0
原创粉丝点击