Tuesday, July 26, 2016

Primality test using BigDecimal

Test this code here: https://www.compilejava.net/
Delete all of the code on the online compiler website and just copy and paste this code to the website as it is. Then click the button "compile and execute".

The result
By the way, this code is using a function "square root using BigDecimal".

import java.math.BigDecimal;
import java.math.MathContext;

public class HelloWorld
{
   public static void main(String[] args)
   {
       BigDecimal test1 = new BigDecimal(4);
       display(test1);
       BigDecimal test2 = new BigDecimal(3);
       display(test2);
       //If the number is larger than integer scope, pass the number as string.
       BigDecimal test3 = new BigDecimal("49999991");
       display(test3);
    }

    public static BigDecimal sqrt(BigDecimal a, int scale){

        BigDecimal x = new BigDecimal(Math.sqrt(a.doubleValue()), MathContext.DECIMAL64);
        if(scale < 17) return x;

        BigDecimal b2 = new BigDecimal(2);
        for(int tempScale = 16; tempScale < scale; tempScale *= 2){
            //x = x - (x * x - a) / (2 * x);
            x = x.subtract(
                    x.multiply(x).subtract(a).divide(
                    x.multiply(b2), scale, BigDecimal.ROUND_HALF_EVEN));
        }
        return x;
    }

 private static void display(BigDecimal Num)
    {
         if( isPrimeNum( Num ) ) {
            System.out.println( Num + " is a prime number." );
         } else{
            System.out.println( Num +" isn't a prime number.");
         }
      }

   private static boolean isPrimeNum( BigDecimal x )
   {
       BigDecimal zero = new BigDecimal(0);
       BigDecimal two = new BigDecimal(2);
       BigDecimal three = new BigDecimal(3);
       
         if( x.compareTo(two) == 0 )
         {      
          return true;
         }
       
         if( x.compareTo(two) < 0 || x.remainder(two).compareTo(zero) == 0 )
         {
         
          return false;
         }
 
         for(BigDecimal a = new BigDecimal(3); a.compareTo(sqrt(x, 2)) <= 0; a = a.add(two) )
         {
           if( x.remainder(a).compareTo(zero) == 0 )
           {
             return false;
           }
         }

     return true;
   }
}