Collat​​z功能

时间:2012-11-18 13:07:42

标签: c++ math

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

我想为初始值1到1000产生停止时间。输出打印'i的停止值为_'为1< = i< = 1000。这是我失败的代码,用于查找初始值2到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。有没有办法避免这种情况产生正确的结果?

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:0)

我可以在上面的代码中看到语法错误:for循环中有,,其中应该有;

正如您所观察到的,主要问题是每次执行while循环时c变量都会重置为1.

可能最好的解决方案是将用于查找停止值的代码放入单独的函数中,然后传递迭代器变量。 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循环体开头的迭代器。