Tuesday 7 June 2016

JavaBIgInteger - A very important tool

Hello everybody !!
It has  been long  since  i  wrote something on my  blog .

I had  to take a gap due to my exams and vacations . This time i am gonna tell you about the benifits of Biginteger class of  java .
BigInteger class of java can be imported from math class of java . There are  several benifits of using BigInteger class which puts the java  user a way ahead  than C/c++ users in  certain aspects.
For Example : if  you are  required to find 25! ,,  there  are  no  any  built in data types in C/c++ which can store such a big value.
If you try finding 25! using C/C++ ,  it  would take you very complex method  to  do so . Fortunately we can solve it  easily in Java using BigInteger .

BigInteger class supports basic integer operations  in it . Some of the useful methods are :
addition : add(BI)  //BI-> BigInteger type
substraction : substract(BI)
multiplication : multiply(BI)
divide : divide(BI)
remainder : remainder(BI)
modular : mod(BI)

 javaBigInteger has several other  bonus features that can be useful during programming
contests—in terms of shortening the code length—compared to if we have to write these
functions ourselves. Java BigInteger class happens to have a built-in base number converter:
The class’s constructor and function toString(int radix), a very good (but probabilistic)
prime testing function isProbablePrime(int certainty), a GCD routine gcd(BI), and a
modular arithmetic function modPow(BI exponent, BI m)

the  following  program shows how to calculate 25! using BigInteger :

import java.util.*;
import java.math.*;

class Factorial{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n= 25,i,j,k;
BigInteger product = BigInteger.ONE;// BigInteger has special cnstants like ZERO,ONE,TEN etc
for(i=1;i<=n;i++)
{
product = product.multiply(BigInteger.valueOf(i)); // here we cant write i directly ,, coz integer needs to be typecasted in BigInteger here

}
System.out.println("The value of your faactorial is  = " + product);

}
}


Base number conversion using BigInteger :
given a base b and two  positive integers p and m in base b.We have to compute p%m in base b .
i.e if we have b=2 , p = 110 ,m = 011 .  answer should be 010 . i.e 5%3 = 2.
the following solution explains this :

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
int b = sc.nextInt();
if (b == 0) break; // special class’s constructor!
BigInteger p = new BigInteger(sc.next(), b); // the second parameter
BigInteger m = new BigInteger(sc.next(), b); // is the base
System.out.println((p.mod(m)).toString(b)); // can output in any base
} } }