In the Recursion when I write res += countNatNum(++len, sum + i, k, d);
I have a StackOverFlow mistake. But when I change pre-increment on len + 1
res res += countNatNum(len + 1, sum + i, k, d);
everything is OK. I don't understand why does it happen because I check the condition with if (len == 3)
?
public static int countNatNum(int len, int sum, int k, int d){
int base = 9;
if (d > base * k) return 0;
else if (len == k){
if (sum == d){
return 1;
}
else return 0;
}
int res = 0;
int c = (len == 0 ? 1 : 0);
for (int i = c; i <= base; i++){
res += countNatNum(len + 1, sum + i, k, d);
}
return res;
}
}
The Program should count the number of natural numbers where sum of digits == another natural number. The program works correct but i don't understand why does pre-increment works in such strange way.