dimanche 23 août 2015

Error in my 3n+1 code

Can someone see the bug in my C++ code (C++11 g++ 4.9.1) for the 3n+1 problem at PEG.

Pick a positive integer n. If it is odd, multiply it by three and then add one. Otherwise (if it is even), divide it by two. The positive integer obtained is the new n, and this procedure is repeated.

It is believed that n will eventually become 1 (this is called the Collatz conjecture.) Computers have checked that any value of n less than 5×1018 does, indeed, eventually become 1 if this procedure is applied enough times.

You will be given the value of n. Determine how many times this procedure must be applied before n becomes 1.

#include <iostream>
using namespace std;

int main() {
    unsigned long long collatz(unsigned long long), test, k=0;
    cin >> test;

    do {
        test = collatz(test);
        k++;
    } while(test!=1);

    cout << k;
    return 0;
}

unsigned long long collatz(unsigned long long x) {
    return (x%2==0) ? x/2 : 3*x+1;
}

Aucun commentaire:

Enregistrer un commentaire