2014年2月8日 星期六

UVa OJ - 100 The 3n + 1 problem

The following program is my ACcepted code for UVA-100.
It's a for everybody to learn and discuss.
If there is any mistake or comment, please let me know.  :D

此乃UAV 100的AC code!
歡迎一同討論學習,如有錯誤與任何建議請留言 : )

//This program is for UVA 100 The 3n + 1 problem
//http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36



#include<stdio.h>
#include<iostream>
#include<stdlib.h>
using namespace std;

int three_n_plus_one(int n)
{
    int cycle = 1;
   
    while(n != 1)
    {
        if( n% 2 )//n%2 is true when n is odd
            n = n * 3 + 1;
        else
            n = n/2;
        cycle ++;
    }
    return cycle;
}

int findMaxCycle(int x, int y)
{
    int max = 0, tmp;
   
    for(int i=x; i<=y; i++)
    {
        tmp = three_n_plus_one(i);
        max = tmp > max? tmp: max;
    }
    return max;
}

int main()
{
    int x, y, ans;//x and y as the problem's i and j
   
    while(scanf("%d %d", &x, &y)!=EOF)
    {  
        if(x <= y)
            ans = findMaxCycle(x, y);
        else
            ans = findMaxCycle(y, x);
       
        printf("%d %d %d\n", x, y, ans);
    }
   
    return 0;
}


Please feel free to use it after adding this blog as an reference. (http://autekroy.blogspot.tw) If there is any mistake or comment, please let me know. :D 

歡迎使用與分享任何內容,但請記得標示此部落格為出處。(http://autekroy.blogspot.tw/) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )

沒有留言:

張貼留言

請留下您的任何想法或建議!
Please leave any thought or comment!