Collat​​z函数 [英] Collatz function

查看:176
本文介绍了Collat​​z函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

collat​​z功能 http://en.wikipedia.org/wiki/Collat​​z_conjecture 是一个函数,其取奇数正整数n到3 * n + 1和偶数正整数n到n / 2。它是递归的,因此函数的先前值是函数的下一个值的输入。 Collat​​z猜想说,无论什么初始数(有限),都会有有限数量的递归,直到函数首先取值1.这个递归数被称为初始值的停止时间。

The collatz function http://en.wikipedia.org/wiki/Collatz_conjecture is a function which takes an odd positive integer n to 3*n+1 and an even positive integer n to n/2. It is recursive so the previous value of the function is the input for the next value of the function. The Collatz conjecture says that no matter what the initial number (finite) there will be a finite number of recursions until the function first takes a value of 1. This number of recursions is called the stopping time of the initial value.

我想为初始值1到1000产生停止时间。使用输出打印'1的停止值为_',1 <= i <= 1000。这是一个我的失败的代码,找到初始值2到1000的停止时间:

I want to produce stopping times for initial values 1 to 1000. With the output printing 'The stopping value for i is _' for 1<=i<=1000. Here is a my failed code for finding the stopping time for initial values 2 to 1000:

#include <iostream>
using namespace std;

int main()
{
for(long c=2, c<=1000; c++) // define stopping value as 0 for c=1 elsewhere
{
long count=0;

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

    }

    count ++;
}


cout << "The stopping value for " << c << " is " << count << endl;

}

return 0;
}



我知道为什么这个for循环失败,因为c在while循环中变为1 。有没有办法避免这种情况产生正确的结果?

I know why this for loop fails as the c becomes 1 in the while loop. Is there a way to avoid this to produce a correct result?

任何帮助。

推荐答案

我可以在上面的代码中看到一个语法错误:在$循环中有一个,应该有一个 ; c>。

I can see a syntax error in the code above: there is a , inside the for loop where there should be a ;.

正如你所观察到的,主要的问题是 c

The main problem, as you have observed, is that the c variable is reset to 1 every time as the while loop is performed.

可能最简单的解决方案是将用于查找停止值的代码放入单独的函数中,并且然后传递您的迭代器变量。例如

Probably the neatest solution would be to put the code for finding the stopping value into a separate function, and then passing your iterator variable. e.g.

long stoppingValue(long c)
{
    long count=0;

    while (c!=1)
    {
        ...
    }
    return count;
}

for(long c=2; c<=1000; c++)
{
    cout << "The stopping value for " << c << " is " << stoppingValue(c) << endl;
}

或者,您可以为迭代器变量或工作变量找到一个新名称,并将工作变量设置为等于for循环体开始处的迭代器。

Alternatively, you could find a new name for your iterator variable or your working variable, and set the working variable equal to the iterator at the start of the for loop body.

这篇关于Collat​​z函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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