Saturday, July 23, 2011

The 3n + 1 problem

// 程式若輸入一整數,就會輸出the 3n+1problem的數列,以及經幾步之後會達到1


// test 1.cpp : 定義主控台應用程式的進入點。
//

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>

using namespace std;


int threenja1(int *, int);


int main(int argc, _TCHAR* argv[])
{

    int ptr[300] = {0};
    int length = 0;
    int n = 1; int i;

   
    while (n != 0)
    {

    cout << "Please input a positive integer  n: \n  (Enter 0 to end the program) ";
    cin >> n;

        if ( n > 0 )
        {
            length = threenja1(ptr,n);

            cout << "length = " << length << endl;


            cout << "the process is : \n";
            for ( i = 0; i < length; i ++)
                cout << *(ptr + i) << "  ";

            cout << endl << endl;
        }
       
        else if (n < 0)
        {
            cout << n << " is not a positive integer. \n\n";
        }

        else
        {    cout << "The program is ended. \n\n" ;
            break;
        }



    }


    system("pause");
    return 0;
}


int threenja1(int *ptr , int n)
{
    int i = 1;

    *ptr = n;

    while ( n != 1 )
    {
        if ( n%2 == 0 )
        {   
            n = n/2;
            ptr[i] = n;
            i ++ ;
        }
        else
        {   
            n = 3*n + 1;
            ptr[i] = n;
            i ++ ;
        }
    }

    const int j = i;
    int  *p  = new int[j];

   
    for ( int k = 0 ; k < j ; k++) ;
        *(p + j) = ptr[j];

    ptr = p;

    return i;

}

No comments:

Post a Comment