0

所以我尝试解决这个问题,但我的程序表现得很奇怪。

#include <iostream>
using namespace std;

int triangle_numbers(int n, int meh = 0)
{
    int count = 0;

    //calculate how many divisors there are for meh
    for(int i = 1; i <= meh; i++)
        if(meh%i == 0)
            count++;

    //if the number of divisors for meh is over 500, return meh
    if(count > 500)
        return meh;

    //recursive call to increment n by 1 and set meh to the next triangle number
    triangle_numbers(n+1, meh += n);
}

int main()
{
    int cc = triangle_numbers(1);
    cout << cc << endl;
}

如果我单独输出mehcount我会得到准确的结果,所以我不确定为什么我的程序给了我相同的数字(4246934),即使我这样做了,比如说if(count > 10)。我有一种感觉,这可能与我的递归调用有关,但到目前为止我尝试过的一切都没有奏效。有什么帮助吗?

4

1 回答 1

3

您缺少return完成递归所必需的最终语句(编译器不是警告说triangle_numbers实际上并非在所有情况下都返回某些东西吗?)。

计算出最终值后meh,您需要

return triangle_numbers(n+1, meh += n);

这样meh就可以一路返回调用栈,最后返回到main.

您现在看到的数字可能是递归结束后留在堆栈上的值。

旁注:该算法中的一个经典优化是i迭代到meh / 2但不再进行。显然,大于一半的数字meh不能均匀地划分它,因此可以跳过它们。

于 2012-08-16T21:57:34.233 回答