Wednesday, July 2, 2014

UVa - 694 - The Collatz Sequence

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
long long collatz(long long n, long long limit){
    if(n > limit)return 0;
    if(n == 1)return 1;
    if(n % 2 == 0)return 1 + collatz(n / 2, limit);
    else return 1 + collatz(3 * n + 1, limit);
}
int main(){
    long long n, L, i;
    long long c = 1;
    while(cin >> n >> L){
        if(n < 0 && L < 0)break;
        i = collatz(n, L);
        cout << "Case " << c << ": A = " << n << ", limit = " << L;
        cout << ", number of terms = " << i << endl;
        c++;
    }
    return 0;
}

No comments:

Post a Comment