How to solve Exception in thread “main” java.lang.ArithmeticException: / by zero? -



How to solve Exception in thread “main” java.lang.ArithmeticException: / by zero? -

here code :

import java.io.file; import java.io.filenotfoundexception; import java.io.ioexception; import java.util.scanner; public class prob_c { public static void main(string args[]) throws ioexception { scanner x = null; seek { x = new scanner(new file("prob_c.in")); } grab (filenotfoundexception ex) { system.out.print("file not found!"); } (int = 0; < 10; a++) { int counter = 0; int n = x.nextint(); int r = x.nextint(); counter++; long res = 1; res = getfact(n) / (getfact(n - r) * getfact(r)); system.out.println(res); } } public static long getfact(int j) { long f = 1; (int = j; >= 1; i--) { f *= i; } homecoming f; } }

to deal big factorials, you'll need utilize biginteger class, rather long store numbers.

you can work out getfact(n) / (getfact(n - r) * getfact(r)) far more efficiently if either multiply numbers n downwards n - r + 1 , split getfact(r), or multiply numbers n downwards r + 1 , split getfact(n - r).

the reason you're getting split 0 error binary expansions of factorials tend end lots of zeroes. example, if write 20! in binary, ends 18 zeroes (if i've counted correctly). work out factorial, every time multiply number, more zeroes on end.

now, if take number ends in 64 or more zeroes, , seek fit long, lastly 64 digits truncated - integer overflow. means getfact(n - r) * getfact(r) can truncated zero, if n - r or r big enough. that's partition 0 error coming from.

java exception combinations

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -