java - StackOverflowError In Finding No of Ways -
hi trying write java code problem statement :
find no of ways of distributing n coins m members 1 of them captain(distributor). each member can take 1 coin @ time , pass other members including captain. captain cant have first coin. however, when there 1 coin left the coin should given captain. how many ways possible ?
i tied this. getting stackoverflowerror
. please help.
here making starting call solve(1,n)
private static int solve(int r, int n) { int count = 0; if(n==2 && r!=1) { return 1; } if(n==2 && r==1) { return 2; } for(int i=1;i<=m;i++) { if(r!=i) count += solve(i,--n); } return count; }
stack trace
exception in thread "main" java.lang.stackoverflowerror @ noprey.solve(noprey.java:50) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:62) @ noprey.solve(noprey.java:
this understand error.
this happening because value of n going negative. put , system.out.println(r + "\t\t" + n);
@ start of method , run again. n=4
m=3
, initial value of r=1
.
public static void main(string[] args) throws filenotfoundexception { solve(1, 4); } private static int solve(int r, int n) { system.out.println(r + "\t\t" + n); // rest of code same.
output before error:
1 4 2 3 1 2 3 1 1 0 2 -1 1 -2 2 -3 1 -4 2 -5 1 -6 2 -7 1 -8
Comments
Post a Comment