UVA - 694 The Collatz Sequence

    xiaoxiao2025-06-11  34

    题目大意:给出数字 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; }
    转载请注明原文地址: https://ju.6miu.com/read-1299844.html
    最新回复(0)