[ create a new paste ] login | about

Link: http://codepad.org/R1hhQfbm    [ raw code | output | fork ]

C++, pasted on Oct 25:
// C++11
#include <stdio.h>
#include <stdlib.h>

bool is_odd(unsigned n)
{
    return n % 2 == 1;
}

bool is_even(unsigned n)
{
    return not is_odd(n);
}

#ifndef ACC
int cycle_length(unsigned n, unsigned ignored)
{
   if(n == 1)
       return 1;
   if(is_odd(n))
       return 1 + cycle_length(3 * n + 1, 1);
   if(is_even(n))
       return 1 + cycle_length(n / 2, 1);
}
#else
int cycle_length(unsigned n, int acc)
{
   if(n == 1)
       return acc;
   if(is_odd(n))
       return cycle_length(3 * n + 1, acc + 1);
   if(is_even(n))
       return cycle_length(n / 2, acc + 1);
}
#endif

int main(int argc, char** argv)
{
    unsigned N = argc > 1 ? atoi(argv[1]) : 1000000;
    auto sum = 0u;

    for(auto i = 1u; i < N; ++i)
        sum += cycle_length(i, 1);

    printf("Sum: %d\n", sum);
}


Output:
1
2
3
In function 'int main(int, char**)':
Line 40: error: ISO C++ forbids declaration of 'sum' with no type
compilation terminated due to -Wfatal-errors.


Create a new paste based on this one


Comments: