Java BigInt Class: Adding Two Objects with Carryover | Plus Method

  • Comp Sci
  • Thread starter apiwowar
  • Start date
  • Tags
    Java
In summary: I'm not sure. I'll have to look at your code again. In summary, the class called BigInt has a size and digit. size is the number of digits in the integer that is entered and digit is an array that holds the integer. Theres a method in the class called plus which is supposed to add two BigInts together. If there is a remainder the remainder is supposed to carry over like in regular addition. This is how the numbers are passed from the main class to the BigInt Class. I'm not sure if I passed in the number correctly. or if I made the sum array correctly. When you enter code in a post, put (code) and (/code) tags around it
  • #1
apiwowar
96
0
Thers a class called BigInt and it has a size and digit. size is the number of digits in the integer that is entered and digit is an array that holds the integer.

Theres a method in the class called plus which is supposed to add two BigInts together. If there is a remainder the remainder is supposed to carry over like in regular addition.

This is how the numbers are passed from the main class to the BigInt Class.
num2 = num.plus(num1);

Below is the method that I am working on right now to add the two BigInts.

public BigInt plus(BigInt arg) { // add two BigIntís
BigInt number = arg;
BigInt sum = new BigInt();
sum.digit = new int[50];
int remainder = 0;
for(int i = 0; i <= size; i++)
sum.digit = this.digit + number.digit + remainder;


return sum;

}
I'm not even sure if i passed in the number correctly. or if i made the sum array correctly.

I know that the for loop is going to be used to add the two BigInts but I am not sure where they start or where they end because I am not sure about what I am passing into this method.

Was i right when i said this.digit?

I know there has to be a mod in an if statement that gives remainder a new value if the sum is greater than 9. I just wanted to get this rough method to print something out before i went any further.

any help would be appreciated. If needed, i can add the entire main class and BigInt Class for clarity.
 
Physics news on Phys.org
  • #2
When you enter code in a post, put (code) and (/code) tags around it (but use brackets - [ and ], not parentheses). I have done this with your code.

This will preserve your indentation, and can help make the code easier to read.
apiwowar said:
Thers a class called BigInt and it has a size and digit. size is the number of digits in the integer that is entered and digit is an array that holds the integer.

Theres a method in the class called plus which is supposed to add two BigInts together. If there is a remainder the remainder is supposed to carry over like in regular addition.

This is how the numbers are passed from the main class to the BigInt Class.
num2 = num.plus(num1);

Below is the method that I am working on right now to add the two BigInts.
Code:
public BigInt plus(BigInt arg) { // add two BigIntís 
   BigInt number = arg;
   BigInt sum = new BigInt();
   sum.digit = new int[50];
   int remainder = 0;
   for(int i = 0; i <= size; i++)
      sum.digit[i] = this.digit[i] + number.digit[i] + remainder;
		
   return sum;
}
Yeah, you passed the number correctly, but you don't need an extra local variable to hold it. I.e., you don't need "number". The parameter "arg" already has the number in it.

You do need a variable for the sum, which you have in the 2nd line of code.

In your 3rd line of code, you are assuming that there will be no more than 50 digits in the sum? Is that a reasonable assumption? You didn't give any information as to limitations on the size of a BigInt.

Your for loop won't work correctly, as you are adding from the wrong end. When you add two integers together, you start by adding the 1's place of both numbers, then the 10's place, and so on. Your code starts from the other end.

Also, there is no guarantee that both numbers to be added have the same number of digits. For example, if you were adding 123456789 and 1111, your code would get 234556789, which is incorrect. Instead what you need to to is add 9 and 1 (which gives you a carry), and then 8 and 1 plus the carry, and so on, moving right to left until you run out of digits.

Finally, what you are calling "remainder" is usually called the carry. The term "remainder" implies that division is going on, not addition. Your code sets remainder to 0, and then never resets it to any other value, so inside the loop you will always be adding 0.

To fix your code, manually (with paper and pencil) go through the steps of adding two numbers together. That should give you a better idea of what your routine needs to do.




apiwowar said:
I'm not even sure if i passed in the number correctly. or if i made the sum array correctly.

I know that the for loop is going to be used to add the two BigInts but I am not sure where they start or where they end because I am not sure about what I am passing into this method.

Was i right when i said this.digit?

I know there has to be a mod in an if statement that gives remainder a new value if the sum is greater than 9. I just wanted to get this rough method to print something out before i went any further.
Yes. Each time you add two digits, there should be an if statement to check to see whether the sum of those two digits was greater than 9. If so, you will need to carry 1 to the next higher place.
apiwowar said:
any help would be appreciated. If needed, i can add the entire main class and BigInt Class for clarity.
 
  • #3
The BigInt won't be bigger than 50 digits.

I know that my for loop is wrong. I tried to just have it start at 50 and end at 0 but it gave me an out of bounds error: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50

What i was thinking of doing was comparing the size of the two BigInts. Could i just do that by writing an if statement that would compare this.size and arg.size to see which one is bigger and then set the for loop to start at this.size(if it turned out to be bigger) and end at 0?


This is what i have so far

Code:
 public BigInt plus(BigInt arg) { // add two BigIntís 
		
		BigInt sum = new BigInt();
		sum.digit = new int[50];
		int carry = 0; 
			for(int i = 50; i > 0; i--){
				
				sum.digit[i] = this.digit[i] + arg.digit[i] + carry;//adds two BigInts and possible carry
					if(sum.digit[i] > 9){ //to extract carry if the sum is greater than 9
					sum.digit[i] = sum.digit[i] % 10;//extract the ones place
					carry = sum.digit[i] / 10;//extract the carry
					}
					
				}	
		
		return sum;
 		
	}
 
  • #4
If your array has 50 numbers in it, the indexes run from 0 through 49. Trying to access the element at index 50 is what caused the exception you got.

What you have looks pretty close. Change your loop to
for (int i = 49; i >= 0; i--)

BTW, I formatted your code to make it a little more readable, mostly by undoing some of the indentation you have, which makes your code spread way to the right on the page here.
Code:
public BigInt plus(BigInt arg) 
{ // add two BigIntís 
		
   BigInt sum = new BigInt();
   sum.digit = new int[50];
   int carry = 0; 
   for(int i = 50; i > 0; i--)
   {
      sum.digit[i] = this.digit[i] + arg.digit[i] + carry;//adds two BigInts and possible carry
      if(sum.digit[i] > 9){ //to extract carry if the sum is greater than 9
         sum.digit[i] = sum.digit[i] % 10;//extract the ones place
         carry = sum.digit[i] / 10;//extract the carry
      }
					
   }	
   return sum;
}
 
  • #5
i made that change. it adds the digits in the ones place but that's all it does. I haven't figured out why it does that. Also, if i add 999 + 1 it returns 990. Should i create an if statement or something that does the carry for everything except the first element so that it can become 1000?
 
  • #6
You already have an if statement.

You are calculating the carry value too late. All you need to do is reverse the order of the two statements in your if statement.
 
  • #7
I can add as long as the sum is less than 1000, if the sum is over 1000. if i set the first number equal to 800 and the second number equal to 201 it gives me 012 as the sum. But if i put in 800 and 151, for example, 951 will print out as the sum.

This is what i changed it to

Code:
 public BigInt plus(BigInt arg) { // add two BigInt’s 
		
		BigInt sum = new BigInt();//Create sum object
		int carry = 0; //declare and intialize carry
		int i;
		//change size of sum
		if(this.size > arg.size)
			sum.size = this.size;
		else
			sum.size = arg.size;
		
		//add two BigInts
		
			for(i = sum.size - 1; i >= 0; i--){
				sum.digit[i] = this.digit[i] + arg.digit[i] + carry;
				
				if(sum.digit[i] > 9){
				carry = sum.digit[i] / 10;
				sum.digit[i] = sum.digit[i] % 10;
					
				}//closes if
				else{
				sum.digit[i] = sum.digit[i];
				}
			}//closes for
		
		return sum;
 		
	}//closes plus
 
  • #8
apiwowar said:
I can add as long as the sum is less than 1000, if the sum is over 1000. if i set the first number equal to 800 and the second number equal to 201 it gives me 012 as the sum. But if i put in 800 and 151, for example, 951 will print out as the sum.

This is what i changed it to
I reformatted your code, as it was indented too much, and I had to scroll across to see the ends of some lines. Don't indent the top line of a for loop - just the body.
apiwowar said:
Code:
public BigInt plus(BigInt arg) { // add two BigInt’s 
		
	BigInt sum = new BigInt();//Create sum object
	int carry = 0; //declare and intialize carry
	int i;
	//change size of sum
	if(this.size > arg.size)
   	   sum.size = this.size;
	else
	   sum.size = arg.size;
		
	//add two BigInts
		
	for(i = sum.size - 1; i >= 0; i--){
	    sum.digit[i] = this.digit[i] + arg.digit[i] + carry;
				
	    if(sum.digit[i] > 9){
	       carry = sum.digit[i] / 10;
	       sum.digit[i] = sum.digit[i] % 10;
	    }//closes if
	    else{
	       sum.digit[i] = sum.digit[i];
	    }
	}//closes for
		
	return sum;
 		
}//closes plus

Your code is different from what you posted before, particularly the part where you are fiddling with the size of the argument. You should not be doing this. It will often be the case that sum will have more digits in it than either of the two numbers being added together. Think about the example you gave, where you're adding together 800 and 201. The sum is 1001. Your answer of 021 indicates at least two problems: sum is being truncated, and your addition is wrong as well, possibly because you have three lines of code where sum.digit is being written to. You should be doing that only once.

Here's some pseudocode for what each iteration of your loop should be doing. The <-- symbol means "is set to".
Code:
temp <-- this.digit[i] + arg.digit[i] + carry
sum.digit[i] <-- temp % 10
carry <-- temp / 10
 
  • #9
This is what i changed it to. Now when it runs i get this message:
Exception in thread "main" java.lang.NullPointerException
at BigInt.plus(BigInt.java:69)
at BigIntTest.main(BigIntTest.java:28)

Whats that?




Code:
public BigInt plus(BigInt arg) { // add two BigIntís 
		
		BigInt sum = new BigInt();//Create sum object
		int carry = 0; //declare and intialize carry
		int i, temp;
		
		
		//add two BigInts
		
		for(i = 49; i >= 0; i--){
		        temp = this.digit[i] + arg.digit[i] + carry;
				
			if(temp > 9){
			sum.digit[i] = temp % 10;
			carry = temp / 10;	
			}//closes if
			else{
			sum.digit[i] = temp;
			}
		}//closes for
		
	return sum;
 		
}//closes plus
 
  • #10
I don't know why you're getting that exception. There is something going on at line # 69 in your plus method, and at line #28 in your main method.

Show me all of your code and I'm sure we can figure it out.
 
  • #11
This is the main
Code:
public class BigIntTest {

   public static void main(String[] args) {
      int count, i;
      BigInt num, num1, num2 = new BigInt("1");
      BigInt zero = new BigInt();
      System.out.print("First BigInt's: " + new BigInt(233334));
      System.out.print(", " + new BigInt("567"));
      System.out.print(", " + new BigInt(230));
      System.out.print(", " + new BigInt("0"));
      System.out.println(", " + num2 + ", " + zero);
      System.out.println(); 
      // plus tester
     	num = new BigInt(999);
      num1 = new BigInt(1);
      num2 = new BigInt(num);
		
		//Test bigInts
		System.out.println("Num " + num);
		System.out.println("Num1 " + num1);
		System.out.println("Num2 " + num2);
		
		System.out.println("\n Num + num1= " + num.plus(num1));
		
		
      for (count = 1; count <= 188; count++){    
		 
			num2 = num.plus(num1);
         num = new BigInt(num1);
         num1 = new BigInt(num2);
         //num1.inc();
         //num2.inc();
         //num.inc();
         if (count <= 13)
            System.out.print(num1 + " ");
         else
            if (count % 50 == 38) {
               System.out.println();
               System.out.print(num1);
            }
      }
      System.out.println();
      System.out.println();
       // times tester
      BigInt[] val = new BigInt[3];
      BigInt temp;
      val[0] = new BigInt(95);
      temp = new BigInt(95);
      for (i = 1; i<= 10; i++) {
         for (count = 1; count <= 4; count++)
            val[0] = val[0].times(val[0]);
         System.out.println(val[0]);
         val[0] = temp.plus(new BigInt(i));
      }
      val[0] = new BigInt(1);
      val[1] = new BigInt(2);
      val[2] = new BigInt(3);
      for (count = 1; count <= 26; count++){
         if (count%2 == 0)
            val[0] = val[0].plus(val[1]);
         else
            val[0] = val[0].times(val[1]);
         if ((val[1].compareTo(val[0]) < 0) && (val[1].compareTo(val[2]) < 0)) {
            temp = val[1];
            val[1] = val[0];
            val[0] = temp;
         } else if ((val[2].compareTo(val[0]) < 0) && (val[2].compareTo(val[1]) < 0)) {
            temp = val[2];
            val[2] = val[0];
            val[0] = temp;
         } 
         if (val[1].compareTo(val[2]) > 0) {
            temp = val[1];
            val[1] = val[2];
            val[2] = temp;
         }
         if (count <= 16) {
            System.out.print(val[0] + "  ");
            System.out.print(val[1] + "  ");
            System.out.print(val[2]);
         } else {
            System.out.println(val[0]);
            System.out.println(val[1]);
            System.out.println(val[2]);
         }
         System.out.println();
      }
      System.out.println(); 
   } 
}

and this is the BigInt class

Code:
class BigInt { 
   private int digit[];         // represent the integer as an array of digits 
   private int size;            // number of digits in the integer 
   private final int max = 50;  // maximum number of digits in the integer 
   public BigInt() {     // default constructor 
   	size = 1;
  		digit = new int[max];
		digit[0] = 0;
  
   } 
   public BigInt(String num) {  // constructor with initial String value 
      size = num.length(); 
      digit = new int[max]; 
      for (int ct = size - 1; ct >= 0; ct --) { 
         digit[ct] = Integer.parseInt(num.substring(size - ct - 1, size - ct)); 
      } 
   } 
   public BigInt(int num) {  // constructor with initial integer value 
	size = Integer.toString(num).length();
	digit = new int[max];
		int rem = num;
		for ( int ct = 0; ct <= size - 1; ct++){
			digit[ct] = rem % 10;
			rem = rem / 10;
			}
   } 
   public BigInt(BigInt num) {  // copy constructor
   BigInt copy = new BigInt();//Create copy object
	copy.size = this.size;//declare and initialize with BigInt nums size
	for(int i = 0; i < this.size; i++)//copy the digits in each index
		copy.digit[i] = this.digit[i];
	
	
	} 
   public String toString() { // override Objectís version 
      String intString = ""; 
      for (int ct = size - 1; ct >= 0; ct --) { 
         intString = intString + String.valueOf(digit[ct]); 
      } 
      return intString; 
   } 
   public int compareTo(BigInt other) { 
       int compare = 0;
		 
		// return  1 if this greater than other 
		 	
		// return -1 if this less than other 
			
		// return  0 if both equal 
			
		
	return compare;//must change	                              
                                       
  	} 
   public BigInt plus(BigInt arg) { // add two BigIntís 
		
		BigInt sum = new BigInt();//Create sum object
		int carry = 0; //declare and intialize carry
		int i, temp;
		
		
		//add two BigInts
		
		for(i = 49; i >= 0; i--){
			temp = this.digit[i] + arg.digit[i] + carry;
				
			if(temp > 9){
			sum.digit[i] = temp % 10;
			carry = temp / 10;	
			}//closes if
			else{
			sum.digit[i] = temp;
			}
		}//closes for
		
	return sum;
 		
}//closes plus 
	
	
   public BigInt times(BigInt other) { // multiply two BigInts 
   BigInt product = new BigInt();
	
	
	return product;
	} 
	
	
   //private void times10() { // I found this useful, but you might not. 
                          // Not required, but if you do write it be careful 
                            // since it changes the BigInt. You might prefer  
                            // writing a version that creates a new BigInt 
   } 



//inc method adds 1 to bigint
 
  • #12
Your BigIntTest file is way too complicated - you're trying to do too many things with stuff that is completely untested and buggy.

BigIntTest.java - first 40 or so lines. Line 28 is marked
Code:
public class BigIntTest {

   public static void main(String[] args) {
      int count, i;
      BigInt num, num1, num2 = new BigInt("1");
      BigInt zero = new BigInt();
      System.out.print("First BigInt's: " + new BigInt(233334));
      System.out.print(", " + new BigInt("567"));
      System.out.print(", " + new BigInt(230));
      System.out.print(", " + new BigInt("0"));
      System.out.println(", " + num2 + ", " + zero);
      System.out.println(); 
      // plus tester
     	num = new BigInt(999);
      num1 = new BigInt(1);
      num2 = new BigInt(num);
		
		//Test bigInts
		System.out.println("Num " + num);
		System.out.println("Num1 " + num1);
		System.out.println("Num2 " + num2);
		
		System.out.println("\n Num + num1= " + num.plus(num1));
		
		
      for (count = 1; count <= 188; count++){    
		 
(28)			num2 = num.plus(num1);
         num = new BigInt(num1);
         num1 = new BigInt(num2);
         //num1.inc();
         //num2.inc();
         //num.inc();
         if (count <= 13)
            System.out.print(num1 + " ");
         else
            if (count % 50 == 38) {
               System.out.println();
               System.out.print(num1);
            }
      }

Why do you have the random indentation? It makes it much more difficult to read your code when the blocks of code jump around all over the place. The only time you should change the indentation is when something unusual, such as a loop or an if block, is happening.
Why is line 28 in a loop that is going to run 188 times?

I would get rid of all of this and start fresh. Declare three BigNum variables, and initialize two of them like so:
Code:
BigNum num1 = new BigNum(800);
BigNum num2 = new BigNum(201);
BigNum num3 = new BigNum();

num3 = num1.plus(num2);

What does this give you?
 
  • #13
that was a program that my professor gave us to test the BigInt class

I made a new main class

Code:
public class BigIntSimpleTest {

	public static void main(String[] args){

	BigInt num1 = new BigInt(800);
	BigInt num2 = new BigInt(201);
	BigInt num3 = new BigInt();
	
	num3 = num1.plus(num2);
	System.out.println("Num1 + Num2 = " + num3);
	
	}
}

but that prints out as 2 which make no sense
 
  • #14
The new code should be using this constructor for num1 and num2.
Code:
   public BigInt(int num) {  // constructor with initial integer value 
	size = Integer.toString(num).length();
	digit = new int[max];
	int rem = num;
	for ( int ct = 0; ct <= size - 1; ct++){
	   digit[ct] = rem % 10;
	   rem = rem / 10;
	}
   }
This code is not working right. It's storing numbers backwards and at the wrong end of the array. For example, the call to BigInt(800) creates an array of digits that looks like this, with the top row being the indexes of the array elements.
0|1|2|3|4| ... |49
0-0-8-0-0-...-0

I don't remember whether Java initializes variables to a default value, so it might be that the array looks like this
0|1|2|3|4| ... |49
0-0-8-@-#-...-&
Here, everything except the 2 zeroes and the 8 is a garbage value.

I would think you want the digits in the array like this:
0|1|2 ... 47|48|49
0-0-0-... -8-0-0
 
  • #15
I see that the numbers are being reversed. I put two print statements for num1 and num2. num1 prints out as 008 and num2 prints out as 102.

what i don't get is why its doing that because i changed the constructor

Code:
  public BigInt(int num) {  // constructor with initial integer value 
	size = Integer.toString(num).length();
	digit = new int[max];
		
		for ( int ct = size - 1; ct >= 0; ct--){
			digit[ct] = num % 10;
			num = num / 10;
			}
   }

if i understand correctly the loop should mod num so that the ones place of the integer goes into the last index of the array but its not doing that.
 
  • #16
apiwowar said:
I see that the numbers are being reversed. I put two print statements for num1 and num2. num1 prints out as 008 and num2 prints out as 102.

what i don't get is why its doing that because i changed the constructor
Your indentation could still use some work. There are more or less standard ways of doing things.

The top line of the for loop SHOULD NOT BE INDENTED, but the body of the loop should be, and the closing brace of the loop should be aligned with the for.
apiwowar said:
Code:
  public BigInt(int num) {  // constructor with initial integer value 
	size = Integer.toString(num).length();
	digit = new int[max];
		
	for ( int ct = size - 1; ct >= 0; ct--){
	   digit[ct] = num % 10;
	   num = num / 10;
	}
   }

if i understand correctly the loop should mod num so that the ones place of the integer goes into the last index of the array but its not doing that.

The constructor above should be working, so it's possible that the reversal is happening somewhere else. Here's how you can test this.
Code:
public class BigIntSimpleTest {

	public static void main(String[] args){

	BigInt num1 = new BigInt(800);
             System.out.println("num1 digits = " + num1.digits); // added
	BigInt num2 = new BigInt(201);
	System.out.println("num2 digits = " + num2.digits); // added
	BigInt num3 = new BigInt();
	
	num3 = num1.plus(num2);
	System.out.println("Num1 + Num2 = " + num3);
	
	}
}
The reason I'm doing this is to see what's in the digits array right after each of the BigNum objects have been created, and looking directly at the array contents. My thought is that when you use print to display a BigNum, it might be that the copy constructor is being called, and I want to narrow things down as much as possible.

If you have a debugger available, and know how to use it, that would be very helpful.

A last comment - since your digit arrays have 50 elements, it would be a very good idea to initialize them before using them. If you don't initialize a variable, its value is whatever garbage happens to be in memory at the time, and that's not good.
 
  • #17
I played around with it and got it to work somehow. it just doesn't work if i want the sum to be greater than 9999. i get an arrayindexoutofboundsexception. i have to play with that to see why its happeneing.

this is my constructor
Code:
 public BigInt(int num) {  // constructor with initial integer value 
		size = Integer.toString(num).length();
		digit = new int[max];
		
		for ( int ct = 0; ct <= size-1; ct++){
			digit[ct] = num % 10;
			num = num / 10;
		}
   }

and this is my plus method

Code:
public BigInt plus(BigInt arg) { // add two BigInt’s 
		
		BigInt sum = new BigInt();//Create sum object
		 //declare and intialize carry
		int carry = 0;	
		int i, temp;
		//change size of sum
		if(this.size > arg.size)
			sum.size = this.size;
		else
			sum.size = arg.size;
		
		//add two BigInts
		
		for(i = 0; i <= sum.size-1; i++){
			
		        temp = this.digit[i] + arg.digit[i];
			temp = temp + carry;
			System.out.println(i + " Temp is " + temp);
			
			sum.digit[i] = temp % 10;
			carry = temp / 10;
				
			if(temp > 9){
			while(sum.digit[i] == sum.digit[sum.size-1]){
			sum.size++;
			System.out.println("The while loop works when i is " + i);
				}
			}
		System.out.println(i + "Carry is " + carry);
		System.out.println("sum.digit[" + i +"] is " + sum.digit[i]);		
		}//closes for
		
		return sum;
 		
	}//closes plus
 
  • #18
There's a problem with your copy constructor. Here's your code:
Code:
public BigInt(BigInt num) {  // copy constructor
   BigInt copy = new BigInt();//Create copy object
	copy.size = this.size;//declare and initialize with BigInt nums size
	for(int i = 0; i < this.size; i++)//copy the digits in each index
		copy.digit[i] = this.digit[i];
	
	
	}

Your code is creating a local object named copy - it should not do this. What it should do is set the class member variables using the member variables on the parameter object, num.

Here's some code - I don't have a Java compiler installed, so I can't guarantee that it will work perfectly, but it's a step in the right direction.

Note how I am indenting things. This is a common style, including always using braces for for loops, even when the loop body is only one line. At the company where I work, this is how they do things.

Code:
// Copy constructor
public BigInt(BigInt num) 
{  
   // Copy member variables from num.
   size = num.size;
   // Copy the digits in each index. 
   for(int i = 0; i < this.size; i++)
   {
      digit[i] = num.digit[i];
   }
}
 
  • #19
is that because the object itself is being created in the main class?

and sorry about the indentation, its been two years since I've done java and I am just starting up again so I am a little rusty.
 
  • #20
apiwowar said:
is that because the object itself is being created in the main class?
I don't understand your question. Are you asking about the copy constructor?
apiwowar said:
and sorry about the indentation, its been two years since I've done java and I am just starting up again so I am a little rusty.

I didn't notice an earlier post from you, where you said that things are working, except for numbers larger than 9999 - something like that.

I'll take a look and reply back to that post.
 
  • #21
yes, the copy constructor you said
Your code is creating a local object named copy - it should not do this. What it should do is set the class member variables using the member variables on the parameter object, num.

and i sort of fixed the problem that i had with that, i had a while loop to increase the size of the sum array but i changed that to an if statement, the problem now is that the if statements conditions are met on every run of the for loop so if i add 99999 + 1 i get 0000100000. I know that i have to change the conditions of my for loop so that it only increases the size if the highest digit in the array increases by one like 999 + 1 or anything that makes the sum have a size that is one greater than the size of what was added in.

this is my plus method now

Code:
public BigInt plus(BigInt arg) { // add two BigIntís 
		
		BigInt sum = new BigInt();//Create sum object
		 //declare and intialize carry
		int carry = 0;	
		int i, temp;
		//change size of sum
		if(this.size > arg.size)
			sum.size = this.size;
		else
			sum.size = arg.size;
		
		//add two BigInts
		
		for(i = 0; i <= sum.size-1; i++){
			
			temp = this.digit[i] + arg.digit[i];
			temp = temp + carry;
			System.out.println(i + " Temp is " + temp);
			
				sum.digit[i] = temp % 10;
				carry = temp / 10;
				System.out.println(i + "Carry is " + carry);
		System.out.println("sum.digit[" + i +"] is " + sum.digit[i]);
			if(temp > 9){
				
				if(sum.digit[i] == sum.digit[sum.size-1]){
					sum.size = sum.size + 1;
					System.out.println("The while loop works when i is " + i);
				}
			}
				
		}//closes for
		
		return sum;
 		
	}//closes plus
 
  • #22
In post #17 you show your code for the plus method and the BigInt(int) constructor. The code for both of these is back to doing things incorrectly, storing the numbers backwards, and in the wrong end of the array.

You could get away with doing things like this, but it's much easier to store numbers in the same way that we are used to looking at them. For example, the digits of 800 should be stored in the digits array as 0000000 ... 800, with 8 at digits[47], 0 at digits[48], and 0 at digits[49]. All other digit elements should be set to 0, which your default constructor is NOT doing, but SHOULD.

Here's your code for the plus method, formatted as I would do it. If you use this formatting style, you will probably get style points from your instructor, as your code will be much easier to read.

You won't need vacuous comments like "//closes for" because it will be obvious where the for loop ends.

Code:
// add two BigInts
public BigInt plus(BigInt arg) 
{  
   // Create sum object		
   BigInt sum = new BigInt();

   // declare and intialize carry
   int carry = 0;	
   int i, temp;

   // change size of sum
   if(this.size > arg.size)
   {
      sum.size = this.size;
   }
   else
   {
      sum.size = arg.size;
   }

   // add two BigInts
   for(i = 0; i <= sum.size-1; i++)
   {
      temp = this.digit[i] + arg.digit[i];
      temp = temp + carry;
      System.out.println(i + " Temp is " + temp);
			
      sum.digit[i] = temp % 10;
      carry = temp / 10;
			
      if(temp > 9)
      {
         while(sum.digit[i] == sum.digit[sum.size-1])
         {
            sum.size++;
            System.out.println("The while loop works when i is " + i);
         }
      }
      System.out.println(i + "Carry is " + carry);
      System.out.println("sum.digit[" + i +"] is " + sum.digit[i]);		
   }//closes for
		
   return sum;
}

There is a lot of extra stuff in there - some good (such as the println statements, which are helpful for debugging), and some not so good.

You can simplify your for loop a LOT, using what I suggested many posts ago, in post #8.
Code:
for (int i = max - 1; i >= 0; i--)
{
   temp = this.digit[i] + arg.digit[i] + carry;
   sum.digit[i] = temp % 10;
   carry = temp / 10;
}
The body of your for loop has more than a dozen lines. The one above has three. Think about how it works.
Case 1: temp is larger than 9, say 12
sum.digit = 2;
carry = 1

Case 2: temp is less than or equal to 9, say 8
sum.digit = 8;
carry = 0;

No if, while or other logic is needed.

Note that the code above depends on the BigInt(int) constructor working correctly, putting the 1's digit at digit[49], the 10's digit at digit[48], the 100's digit at digit[47], and so on all the way down to digit[0]. It would be a good idea for the default constructor and the BigInt(int) constructor to initialize the digit array to all zeroes before doing anything else.

There is another problem with your plus method.
Code:
// change size of sum
if(this.size > arg.size)
   sum.size = this.size;
else
   sum.size = arg.size;

You DON"T want to set sum.size to either this.size or arg.size! Set sum.size to an appropriate value AFTER you have calculated the sum, not BEFORE.

When you add two numbers with the same number of digits, 3/4 of the time you will get a number that has more digits. Consider these three-digit numbers:
600 + 700 = 1300
400 + 800 = 1200
450 + 650 = 1100
450 + 300 = 750

If the two numbers have different sizes, just add them together and set sum.size to the right value after you have done the addition.
 
  • #23
I tried to get the digits into the array the way you said but they ended up going in backwards, 800 would go in as 008 for example which didnt make sense to me.

how would i set sum.size equal to the right size after i added the two numbers? can you give me an idea.
 
  • #24
There are two things you need to fix: your plus routine and your BigInt(int) constructor.

Code:
public BigInt(int num) {  // constructor with initial integer value 
	size = Integer.toString(num).length();
	digit = new int[max];
		int rem = num;
		for ( int ct = 0; ct <= size - 1; ct++){
			digit[ct] = rem % 10;
			rem = rem / 10;
			}
   }

This constructor should look something like this. Please try to format your code as I've done it. Your instructor will thank you.

Code:
// constructor with initial integer value 
public BigInt(int num) 
{  
   size = Integer.toString(num).length();
   digit = new int[max];
  
   int rem = num;
   for ( int ct = max - 1; ct >= 0; ct--)
   {
      digit[ct] = rem % 10;
      rem = rem / 10;
   }
}
If num = 800, size = 3 and the digit array looks like this:
0000 ... 00800

The plus method should add two numbers together starting from the highest array index, 49, and work its way back toward the beginning, just like you normally do addition.

To calculate the size of the sum, start at the beginning of the array (digit[0]) and work toward the end, until you reach the first nonzero number. By keeping track of where the first nonzero digit is, you can calculate the length of the number.

For example, with 000000... 00800, a loop would find the first nonzero number at index 47. The length of this number is 49 - 47 + 1 = 3.
 
  • #25
i tried to change the constructor and the method so that it works from the end of the array but when i put in numbers to test it random numbers that make no sense come out.
 
  • #26
Show me your code for the constructor, the plus method, and the code you're using to test them.
 
  • #27
constructor

Code:
// constructor with initial integer value  
   public BigInt(int num) 
	{  
		size = Integer.toString(num).length();
		digit = new int[max];
		int rem = num;
		for ( int ct = 0; ct <= size - 1; ct++)
		{
			digit[ct] = rem % 10;
			rem = rem / 10;
		}
   }

plus method

Code:
 public BigInt plus(BigInt arg) { // add two BigInt’s 
		
		BigInt sum = new BigInt();//Create sum object
		 //declare and intialize carry
		int carry = 0;	
		int i, temp;
		
		//change size of sum
      if(this.size > arg.size)
         sum.size = this.size;
      else
         sum.size = arg.size;

		//add two BigInts
		
		for(i = 0; i <= sum.size - 1; i++)
		{
			
			temp = this.digit[i] + arg.digit[i] + carry;
			
			System.out.println(i + " Temp is " + temp);
			
				sum.digit[i] = temp % 10;
				carry = temp / 10;
				System.out.println(i + "Carry is " + carry);
		System.out.println("sum.digit[" + i +"] is " + sum.digit[i]);
		
		if(temp > 9){
            
            if(sum.digit[i] == sum.digit[sum.size-1]){
               sum.size = sum.size + 1;
               System.out.println("The while loop works when i is " + i);
            }
	
		}		
		}//closes for
		
		return sum;
 		
	}//closes plus

and the test code

Code:
import java.util.Scanner;

public class BigIntSimpleTest {

	public static void main(String[] args){


	Scanner input = new Scanner(System.in);
	
	int number1 = input.nextInt();
	int number2 = input.nextInt();
	BigInt num1 = new BigInt(number1);
		
	BigInt num2 = new BigInt(number2);
	
	BigInt num3 = new BigInt();
	
	
	System.out.println("Num1 " + num1);
	System.out.println("Num2 " + num2);
	num3 = num1.plus(num2);
	System.out.println("Num1 + Num2 = " + num3);
	
	System.out.println("\ncompare num1 and num2 " + num1.compareTo(num2));
	
	}
}

the formatting is probably bad but I am going to clean it up once i get it to work.

right now it works the only thing is that if the number goes up a digit it adds a leading 0

99 + 1 gives 0100
999 + 1 gives 00100 and so on
 
  • #28
apiwowar said:
the formatting is probably bad but I am going to clean it up once i get it to work.
No - I've been harping at you to clean it up as a favor to me and to your instructor, who will have to read this stuff.

As I've already said, and this is now the THIRD time, you are putting the numbers into the array backwards and at the wrong end.

I feel as though I'm wasting my time and energy with you, so I'm going to bow out.
 
  • #29
I fixed the formatting and changed the constructor so that they work from the highest index to the lowest. I'm not sure what happens though. this is the print out that i get

Num1 99000000000000000000000000000000000000000000000000
Num2 10000000000000000000000000000000000000000000000000
Num1 + Num2 = 00100000000000000000000000000000000000000000000000

and these are my codes which I've tried my best to clean up

constructor

Code:
	// constructor with initial integer value  
   public BigIntAlternate(int num) 
	{  
		size = max;
		digit = new int[max];
		int rem = num;
		for ( int ct = max - 1; ct >= 0; ct--)
		{
			digit[ct] = rem % 10;
			rem = rem / 10;
		}
   }

method

Code:
	// add two BigInt’s 
   public BigIntAlternate plus(BigIntAlternate arg) 
	{ 	
		BigIntAlternate sum = new BigIntAlternate();//Create sum object
		//declare and intialize carry
		int carry = 0;	
		int i, temp;
		
	

		//add two BigInts
		for(i = max - 1; i >= 0; i--)
		{	
		temp = this.digit[i] + arg.digit[i] + carry;	
		sum.digit[i] = temp % 10;
		carry = temp / 10;		
		}
		
	return sum;
 		
	}

and test code

Code:
import java.util.Scanner;

public class BigIntSimpleTestAlt
 {
	public static void main(String[] args)
	{

	Scanner input = new Scanner(System.in);
	
	//int number1 = input.nextInt();
	//int number2 = input.nextInt();
	BigIntAlternate num1 = new BigIntAlternate(99);
		
	BigIntAlternate num2 = new BigIntAlternate(1);
	
	BigIntAlternate num3 = new BigIntAlternate();
	
	
	System.out.println("Num1 " + num1);
	System.out.println("Num2 " + num2);
	num3 = num1.plus(num2);
	System.out.println("Num1 + Num2 = " + num3);
	
	System.out.println("\ncompare num1 and num2 " + num1.compareTo(num2));
	
	}
}
 
  • #30
println is supposed to print an arbitrary object, but your object has two member variables, so that might be at the root of your problems with things being displayed backwards.

Instead of this:
Code:
	System.out.println("Num1 " + num1);
	System.out.println("Num2 " + num2);
	num3 = num1.plus(num2);
	System.out.println("Num1 + Num2 = " + num3);

try this:
Code:
// System.out.println("Num1 " + num1);
System.out.println("Num1 " + num1.digit);
// System.out.println("Num2 " + num2);
System.out.println("Num2 " + num2.digit);

num3 = num1.plus(num2);
// System.out.println("Num1 + Num2 = " + num3);
System.out.println("Num1 + Num2 = " + num3.digit);

If that doesn't work, use a loop to print out each digit in the array for each number, starting from digit[0].

Do you have a debugger to work with? It would be nice to see how the numbers are stored in memory, rather than relying on print or println to see them.
 
  • #31
i changed my test code to what i posted below. it seems that the numbers go in right. num3.digit[47] is 1, num3.digit[48] is 0 and num3.digit[49] is 0 and everything before 47 is 0. but if i just print out num 3 it comes out as 001000...

Code:
import java.util.Scanner;

public class BigIntSimpleTestAlt
 {
	public static void main(String[] args)
	{

	Scanner input = new Scanner(System.in);
	
	//int number1 = input.nextInt();
	//int number2 = input.nextInt();
	BigIntAlternate num1 = new BigIntAlternate(99);
		
	BigIntAlternate num2 = new BigIntAlternate(1);
	
	BigIntAlternate num3 = new BigIntAlternate();
	
	num3 = num1.plus(num2);
	for(int i = 0; i <= 49; i++)
	{
	
	
	System.out.println(i + " Num1 + Num2 = " + num3.digit[i]);
	}
	System.out.println("\ncompare num1 and num2 " + num1.compareTo(num2));
	
	}
}
 
  • #32
So don't use print or println to display all of the digits. What you did by using a loop to go through each element in the digit array is fine.

Does this work?
Code:
System.out.print(num3.digit)

An even better solution would be to write print and println methods for your class to display the digit array.

The code would look like this:
Code:
// Display the digits of a BigNum object.
void print(BigNum bn)
{
   for (int i = 0; i < max; i++)
   {
      print(bn.digit[i]);
   }
}

The code for println would be almost identical, except that it would print a newline character after the last digit.

Your last code snippet is much improved, but could use two tweaks - all of the statements in the body of main should be indented, and the body of the for loop should be indented, like the following. I've deleted a few of the lines you aren't using.

Code:
public static void main(String[] args)
{
   BigIntAlternate num1 = new BigIntAlternate(99);
   BigIntAlternate num2 = new BigIntAlternate(1);
   BigIntAlternate num3 = new BigIntAlternate();
	
   num3 = num1.plus(num2);
   for(int i = 0; i <= 49; i++)
   {
      System.out.println(i + " Num1 + Num2 = " + num3.digit[i]);
   }
   System.out.println("\ncompare num1 and num2 " + num1.compareTo(num2));
}
 

1. What is the Java BigInt Class?

The Java BigInt Class is a built-in class in the Java programming language that allows for the representation and manipulation of arbitrarily large integers. It is used when numbers exceed the limit of the primitive data types such as int or long.

2. What is the purpose of the Plus method in the Java BigInt Class?

The Plus method in the Java BigInt Class is used to add two BigInt objects together, taking into account any carryover digits. This is useful when dealing with very large numbers that cannot be represented by primitive data types.

3. How do I use the Plus method to add two BigInt objects with carryover?

To use the Plus method to add two BigInt objects with carryover, you first need to create two BigInt objects using the BigInt(String val) constructor. Then, call the Plus method on one of the objects, passing in the other object as the parameter. The result will be a new BigInt object with the sum of the two original objects, taking into account any carryover digits.

4. Can I use the Plus method to add regular integers?

No, the Plus method in the Java BigInt Class is specifically designed to add two BigInt objects together. If you want to add regular integers, you can use the int or long data types and the regular addition operator (+).

5. Are there any limitations to using the Java BigInt Class?

While the Java BigInt Class allows for the manipulation of very large numbers, it does have some limitations. The main limitation is that it is not as efficient as using primitive data types, so it should only be used when dealing with numbers that exceed the limits of these data types. Additionally, some methods in the Java BigInt Class may have restrictions on the range of numbers they can handle, so it is important to consult the documentation when using these methods.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
23
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
925
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
Back
Top