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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -