Return to Snippet

Revision: 42271
at March 2, 2011 14:24 by dirkchang


Initial Code
/*
 * 3np1.cpp
 *
 *  Created on: Feb 14, 2011
 *      Author: dirk
 */
 
#include <iostream>
#include <algorithm>
 
inline unsigned cycle_len(unsigned n) {
    unsigned c = 1;
    while( n != 1 ) {
        if( n % 2 ) n = 3 * n + 1;
        else n = n / 2;
        ++c;
    }
    return c;
}
 
int main(int argc, char **argv) {
    unsigned i(0), j(0), max(0), start(0), end(0);
 
    while (std::cin >> i) {
        std::cin >> j;
 
        max = 0;
        if(i < j) {
            start = i;
            end = j;
        }
        else {
            start = j;
            end = i;
        }
        for(unsigned x = start; x <= end; ++x) {
            max = std::max(max, cycle_len(x));
        }
        std::cout << i << ' ' << j << ' ' << max << '\n';
    }
}

Initial URL

                                

Initial Description

                                

Initial Title
The 3n + 1 problem

Initial Tags

                                

Initial Language
C++