0

I'm having problem with this code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>

using namespace std;

long long addV(int i) {
    return pow(10,i);
}

int len;

void recurse(int n,long long &ways,int values[],int current=0,int p=0) {
    if(p>len) return;
    if(current>n) return;
    if(current ==n) {
        ways++;
        return;
    }
    int cv = n-current;
    cv/=values[p];

    for(int i=0;i<=cv;i++) {
    recurse(n,ways,values,current+values[p]*i,p+1);
    }
}


int main() {
    int n;
    cin>>n;
    long long ways=0;
    int values[] ={1,2,3};
    len = sizeof(values)/sizeof(int);
    recurse(n,ways,values);
    cout<<ways;
}

The exception comes from (cv/=values[p];) line. Of course the shitty CodeBlocks never shows what the exception is. I'm sure its something easy to fix.

2

2 Answers 2

1
if(p>len)return;

Indeed you've already accessed over boundary when p == len. You need to return once p >= len.

Sign up to request clarification or add additional context in comments.

Comments

1

Because among your ending condition for the recursion is p > len which means that p will be in the range from zero to three (inclusive). And as you know, an array of three entries have the indexes range from zero to two.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.