开发者

recursive function error: "stack overflow"

I wrote this function that supposed to find smallest positive integer that is divisible by every number 1 through 20. I get "stack overflow error", even though, when I test for numbers 1 through 10, it works just fine. here is my code:

#include<iostream>
#include<cstdlib>

using namespace std;

// function prototype
int smallPos(int k, int m,int n);

int main(){
    printf("the smallest positive number that is divisible by 1 through 20 is %d ", smallPos(1,1,13));

}

int smallPos(int k, int n, int m){
    int div=0;
    for(int i = n;i<=m;i++) {
        if (k%i==0) 
            div++;
    } 
    if (div==m) {
        return k;
    } else {
        k+=1;
        smallPos(k,n,m);
    }   
}

Why does it happen? The number shouldn't be that big 开发者_StackOverflowanyway. Thank you!


The final condition (div == m) will never be true. For div to become equal to m, the number k should be divisible by all of the numbers in range [n,m).

Edit: I've reread the text in the printf() call to understand what the function does. You're looking for the first number divisible by all numbers in the range. If my calculations are correct, this number should be the product of all unique prime factors of the numbers in the range. For the range [1,13] (as per the function call, not the text), this number should be:

30030 = 1 * 2 * 3 * 5 * 7 * 9 * 11 * 13

Now, this means you are going to invoke the function recursively over 30,000 times, which is obviously way too many times for the size of stack you're using (defaults are relatively small). For a range this size, you should really consider writing an iterative function instead.

Edit: here's an iterative version that seems to work.

int smallPos ( int n, int m )
{
    int k = 0;
    while ( ++k )
    {
        int count = 0;
        for (int i = n; i<=m; i++)
        {
            if (k%i==0) {
                ++count;
            }
        }
        if (count == (m-n+1)) {
            return k;
        }
    }
    return k;
}

Indeed, the result for smallPos(1,10), the result is 2520. It seems my previous estimate was a lower bound, not a fixed result.


Your smallPos function incurs undefined behaviour since it is not returning a value in all execution paths. You may want to say return smallPos(k,n,m); in the last part (or just return smallPos(k + 1, n, m); in one go).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜