Writing your own BigInteger Class in JAVA

TUTORIAL NO 9

Writing your own BigInteger Class

In this tutorial you will learn: 1.Console Applications 2.Input in console 3.Strings 4.Arrays 5.Conversion of Strings Today I decided to write a different type of tutorial. Instead of working with GUI I decided to make a console application this time only because we didn’t made any console application in our tutorials. So today I am going to teach you how to make a BigInteger class. Integer occupies 8 bytes i.e 32bits in memory and the last 32nd bit is reserved for the sign. What if we want to handle a number greater than 32bit’s. So today we will solve this problem and make our own bigInteger class we will make it only for addition today to keep things simple and you can extend the functionality later on. Basic step: Download and install ECLIPSE and set up a JAVA PROJECT. Then create a new class and name it BigInteger. Then follow the steps 1.IMPORT STATEMENTS First of all write this import statements in your .java file
  1. import java.util.*;
We only need to write this import statement for some of the functions we will be using in our program. The default import of java already includes string manipulation functions so we don’t need to write any more import statement explicitly. 2. WRITING THE BIGINTEGER CLASS
  1. public class BigInteger {
  2.  
  3.         public static void main(String[] args) {
  4.                
  5.                 Scanner input = new Scanner(System.in);
  6.                 String num1 = "";
  7.                 String num2 = "";
  8.                 String ans = ""; //to get the final answer
  9.                 String zero = "0";
  10.                
  11.                 boolean valid_num1 = true;
  12.                 boolean valid_num2 = true;
  13.                
  14.                 int zeros_count = 0;// keeping track of zeros
  15.                 int carry = 0; // keeping track of end carry
  16.                
First of all we write the class and then we write our main function. In this tutorial we will do everything in the main function. First of all we will declare a scanner class object and pass System.in (for input). After that we will declare the two empty strings for taking the inputs. Then we will declare variables for storing the answer and for appending 0 if needed in the second number. The main trick in this program is taking the inputs in a string so that we can take the input of any length and then we will convert it to an integer. TAKING THE INPUTS:
  1. System.out.print("Enter num1 :");
  2.         num1 = input.nextLine();
  3.                
  4.         System.out.print("Enter num2 :");
  5.         num2 = input.nextLine();
Now we will write a print statement and then take an input using the nextLine function which will take a string input. Then we will store the string to num1 variable. After the second print statement we will take the input and store it in the num2 variable which is the number we want to add in the first number CONDITIONS:
  1. if(num1.length() != num2.length()) // if num1 is not equal to num2 then add zeros in the smaller number
  2. {
  3.         if(num1.length()>num2.length()){
  4.             zeros_count = num1.length()-num2.length(); // difference of length of two strings will give us the required number of zeros
  5.             for(int i = 1; i<=zeros_count;i++)
  6.                 num2 = zero+num2;
  7.         }
  8.         else{
  9.             zeros_count = num2.length()-num1.length(); // difference of length of two strings will give us the required number of zeros
  10.             for(int i = 1; i<=zeros_count;i++)
  11.                 num1 = zero+num1;
  12.         }
  13. }
In the conditions we first of all check if length of the first string is not equal to the length of the second string and then we move on to check which number is greater and which one is smaller. Then than we simply subtract the lengths of the smaller number from the greater number so that we get a count of how many zeros we want to append on the left hand side. CHECKING INVALID ENTRIES:
  1. char[] temp_num1 = num1.toCharArray();
  2. char[] temp_num2 = num2.toCharArray();  // converting both number to char array
  3.                
  4. for(int x = 0; x<temp_num1.length; x++) // checking for invalid entries in number1
  5. {
  6.         if((temp_num1[x] < '0' | temp_num1[x] > '9'))
  7.         {
  8.             valid_num1 = false;
  9.             System.out.println("Invalid entries in number1 : "+temp_num1[x]);
  10.         }
  11. }
  12.                
  13. for(int x = 0; x<temp_num2.length; x++) // checking for invalid entries in number2
  14. {
  15.     if((temp_num2[x] < '0' | temp_num2[x] > '9'))
  16.     {
  17.        valid_num2 = false;
  18.        System.out.println("Invalid entries in number2 : "+temp_num2[x]);
  19.         }
  20.                        
  21. }
  22.  
Now we check for the invalid entries in the first and second number. To check for invalid entries we first need to convert both the string numbers to a character array so that we can check character by character. We run a for loop to check character by character we only need to check if the character is less than 0 and greater than 9 because only these numbers are included in the invalid entries and only 0 to 9 are valid entries. So we do this for both the numbers and set the values of our Boolean variables to false if there is any invalid entry in the number.
  1. if((valid_num1 == true) && (valid_num2 == true))
  2. {
  3.         for(int i=temp_num1.length-1; i >= 0; i--)
  4.         {
  5.              if(((temp_num1[i]-'0')+(temp_num2[i])+carry)<='9') //subtracting ascii of 0 and then adding to number2 and the carry
  6.                 {
  7.                   ans=(char) ((temp_num1[i]-'0')+(temp_num2[i])+carry)+ans;    
  8.                   carry = 0;
  9.                 }
  10.                                        
  11.                 else
  12.                 {              
  13.                    ans=(char) (((temp_num1[i])-'0'+(temp_num2[i])+carry)-10)+ans; //subtracting ascii of 0 and then adding to number2 and the end carry
  14.                    carry = 1;
  15.                 }
  16.         }
  17.                        
  18.         if(carry ==1)
  19.                 ans="1"+ans; // if the final end carry is 1 add one to the string
  20.                 System.out.print("\nAns is : "+ans);   
  21.                
  22. }
  23. else
  24.    return;
  25.                
  26.    }//end main
  27. }//end class
  28.  
If the numbers are valid then we proceed forward and first of all remove a character ‘0’ from all the numbers (REMEMBER: this will subtract the ASC2 value of ‘0’ and give us the actual number in integer form). Then we will add the individual numbers together and checking for a carry in each number we know that if the sum of two numbers Is greater than 9 then it will generate a carry for the next number so we set the carry value accordingly and keep adding the numbers until their length is reached. Every time we simply append our result to the answer variable to the left because remember we are starting from the least significant and moving towards the most significant. In the end we simply check for the last carry if it is generated then we append 1 otherwise leave it. This is how we can make our bigInteger class. Output: output

Add new comment