程序为3n + 1问题解决方案 [英] progam for 3n+1 problem solution

查看:88
本文介绍了程序为3n + 1问题解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作一个3n + 1问题的程序..

这个程序给出正确的输出

但问题是有一个永不终止的while循环。 />
i希望在某些条件下终止while循环..

假设我输入0而循环终止.... plz修改此代码....

谢谢你...

这里是我的代码......用c ++



i make a program for 3n+1 problem..
this program give right output
but the problem is that there is while loop which never terminate.
i want terminte the while loop on certain condition..
suppose if i enter 0 while loop termintate....plz modify this code....
thanks in advnce...
here is my code...in c++

#include <iostream.h>

#include<conio.h>

int cycle( long int n)
{
      long int i = 1;

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

        }
        i++;
    }
    return i;
}

int main()
{
    int a, b, low, high,ch;
     cout<<"enter the series of numbers";

    while(cin>>a>>b) {

        if(a < b) {
            low = a;
            high = b;
        } else {
            low = b;
            high = a;
        }

        int max = cycle(low);

        for(int i = low + 1; i <= high; i++) {
            int l = cycle(i);
            if(l > max) {
                max = l;
            }
        }

        cout<<a<<" "<<b<<" "<<max<<"\n";
               }
     getch();
    return 0;

}

推荐答案

请使用额外的if条件并检查mod值为零等于状态。 />


Please use extra if condition and check the mod value with zero equating status.

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


这篇关于程序为3n + 1问题解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆