function - Exception in thread "main" java.lang.StackOverflowError in recursion -


here function fact calculate factorial

static biginteger fact(biginteger n) {     biginteger f=biginteger.one;     biginteger temp;     if(n.compareto(biginteger.one) <= 0)         return f;     f=f.multiply(n).multiply(fact(n.subtract(biginteger.one)));     return f; } 

input: 1 88888

output: exception in thread "main" java.lang.stackoverflowerror   @ java.math.biginteger.multiplybyint(biginteger.java:1523)   @ java.math.biginteger.multiply(biginteger.java:1490)   @ codechef.fact(codechef.java:30)   @ codechef.fact(codechef.java:30)..... 100 times 

how can code run te<=1000000000 ??

this main function:

class codechef  {      public static void main(string[] args)      {          scanner sc = new scanner(system.in);          int t=sc.nextint();          for(int i=0;i<t;i++)         {              int count=0; string te=sc.next();             biginteger n=new biginteger(te);              te=fact(n).tostring();              for(int j=te.length()-1;j>=0;j--)             {                  if(te.charat(j) == '0')                 { count++; }                  else break;              }              system.out.println(count);          }      }  }  

this code running input <=1024, suggests edit >1024...

the problem is, have maximal recursion depth. if want avoid that, can rewrite code without recursion. can done using simple loop. (this code untested):

static biginteger fact(biginteger n){     biginteger f = biginteger.one;     while(n.compareto(biginteger.one) > 0) {         f = f.multiply(n);         n = n.subtract(biginteger.one);     }     return f; } 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -