Results 1 to 15 of 15
  1. #1
    Zora is offline Member
    Join Date
    Sep 2011
    Posts
    21
    Rep Power
    0

    Default Summing 2 Integers Together (not as easy as it sounds)

    Alright, here's the question.

    Write a java program to read two integer numbers each up to 30 digits, and then add them and print the result along with input numbers.. Example: Assume the first number is 39983928349458 and the second number is equal to 92387486729, then the output should be as follow.

    Output:

    39,983,928,349,458+
    92,387,486,729
    --------------------
    40,076,315,836,187

    Note1: You should input your numbers without comma, but the output should be printed with comma as shown in the example.
    Note2: You are not allowed to use java's BigInteger, BigDecimal, or similar classes. You should use arrays and create your own algorithm, otherwise, you will not be marked.
    Seems rather difficult, but I'm currently trying to figure out how to separate each set of 3 numbers. I don't know what I'm supposed to do for 1 and 2 digits. When summing up the 2 inputs together, I actually have to work with each individual digit right? And in that case, I'll have to create an array and initialize the size according to the length of the input.

    Sorry if this sounds like complete BS, I'm not very good with these programming terminologies. Could I get some guidance?

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Step down. Arithmetic calculation and the output representation done separately. Then it will make your life easy. :)

    Did you tried anything yet?

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    The following simple code segment do the calculation part,

    Java Code:
    import java.util.Scanner;
    import java.math.BigInteger;
    
    class AddNumbers {
    	
    	static Scanner console = new Scanner(System.in);
    	
    	public static void main(String[] args) {
    		System.out.println("1st number; ");
    		BigInteger bigInteger1 = new BigInteger(console.next());
    		
    		System.out.println("2nd number; ");
    		BigInteger bigInteger2 = new BigInteger(console.next());
    		
    		BigInteger bigSum = bigInteger1.add(bigInteger2);
    		System.out.println(bigSum);
    	}
    }

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    How funny it is. With the basis stuff I did this in couple of min.

    Java Code:
    import java.util.Scanner;
    import java.math.BigInteger;
    import java.text.*;
    
    
    class AddNumbers {
    	
    	static Scanner console = new Scanner(System.in);
    	
    	public static void main(String[] args) {
    		System.out.print("1st number; ");
    		BigInteger bigInteger1 = new BigInteger(console.next());
    		
    		System.out.print("2nd number; ");
    		BigInteger bigInteger2 = new BigInteger(console.next());
    		
    		BigInteger bigSum = bigInteger1.add(bigInteger2);
    
    		DecimalFormat myFormatter = new DecimalFormat("###,###");
    		String output1 = myFormatter.format(bigInteger1);
    		String output2 = myFormatter.format(bigInteger2);
    		String output3 = myFormatter.format(bigSum);
    		
    		int len1 = output1.length();
    		int len2 = output2.length();
    		int max = (len1 > len2) ? len1 : len2; 
    		int diff = (len1 > len2) ? (len1 - len2) : (len2 - len1);
    		
    		String dum = "";
    		for(int spaces = 0; spaces < diff; spaces++) {
    			dum += " ";
    		}
    		
    		if(len1 < len2) {
    			output1 = dum + output1; 
    		}
    		else {
    			output2 = dum + output2; 
    		}
    		
    		System.out.println("\n" + output1);
    		System.out.println(output2 + " +");
    		
    		for(int index = 0; index < max; index++) {
    			System.out.print("-");
    		}
    		
    		System.out.println("\n" + output3);
    	}
    }

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Quote Originally Posted by Eranga View Post
    The following simple code segment do the calculation part,
    Read note #2 in the assignment text: you're not allowed to use BigIntegers; you're supposed to do it all by yourself ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Oh I miss it. :S

    Still it is possible. By recursive with the integers.

  7. #7
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Bit late, just finish my lunch ;)

    Have a look at the following code segment.


    Java Code:
    import java.util.Scanner;
    
    class AddNumbers {
    	
    	static Scanner console = new Scanner(System.in);
    	
    	public static void main(String[] args) {
    		// Get the first number from the user
    		System.out.print("1st number; ");
    		String strInput1 = console.next();
    		
    		// Get the second number from the user
    		System.out.print("2nd number; ");
    		String strInput2 = console.next();
    		
    		// Identified which one is the lenghty one, not the larger one
    		String max_len = (strInput1.length() > strInput2.length()) ? strInput1 : strInput2;
    		String min_len = (strInput1.length() > strInput2.length()) ? strInput2 : strInput1;
    		
    		// Split into digits and store them in an array
    		String[] digits1 = max_len.split("(?<=.)");
    		String[] digits2 = min_len.split("(?<=.)");
    		
    		// Dummy array to format the smallest array above
    		String[] digits3 = new String[digits1.length];
    		
    		// If the numbers are not in the same size adjust the index on the smallest
    		if(digits1.length > digits2.length) {
    			digits3 = new String[digits1.length];
    			for(int i = 0; i < digits3.length; i++) {
    				digits3[i] = "0";
    			}
    			int iCount = digits3.length;
    			for(int j = (digits2.length - 1); j >= 0 ; j--) {
    				digits3[--iCount] = digits2[j];
    			}
    		}
    
    		int val = 0;
    		int mod = 0;
    		int up = 0;
    		int low = 0;
    		
    		String sum = "";
    		
    		// Addition of two numbers
    		for(int index = (digits1.length - 1); index >= 0; index--) {
    			up = Integer.parseInt(digits1[index]);
    			
    			if(digits1.length > digits2.length)
    				low = Integer.parseInt(digits3[index]);
    			else
    				low = Integer.parseInt(digits2[index]);
    			
    			mod = (up + low + val) % 10;
    			val = (up + low + val) / 10;
    			
    			sum = mod + sum;
    		}
    		
    		// Display the result. Test with any large number :)
    		sum = ((val == 0) ? "" : val) + "" + sum;
    		System.out.println(sum);
    	}
    }
    You have to do the formatting and display accordingly. Since you cannot use BigInteger and all you have to implement yourself the formatting. Simple regex manipulation works fine. Play around and let me know.

    There are many ways to do the same, and I tried my best to keep the solution simple as possible. If you are not clear with anything please let me know. Good luck! :)

  8. #8
    Grkn is offline Member
    Join Date
    Oct 2011
    Posts
    65
    Rep Power
    0

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    It can write your code with 2 int array

    Integer []firstNumber=new Integer[30];
    Integer []secondNumber=new Integer[30];

    you can use byte array for performance issues.

    So as you can see array has 30 digits and each cell (C) ' value must be 0<= C <=9.

    You have to use one more thing.
    Just fill the array with -1 values;


    Ex:
    12345
    1,2,3,4,5
    4-3-2-1-0 //Index of Array that corresponds to value

    //JUST calculating value . You have to design a little different way

    int value=0;
    for(int indexOfArrayCell=0;indexOfArrayCell<array.length;i ndexOfArrayCell++){
    if(indexOfArrayCell !=-1)
    value=value+array[indexOfArrayCell]+pow(10,indexOfArrayCell);
    }

    This is just a small example. You can't use (int value) to get sum. You have to keep those values in array.

  9. #9
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Quote Originally Posted by Grkn View Post
    You can't use (int value) to get sum. You have to keep those values in array.
    What you mean by this?

  10. #10
    Grkn is offline Member
    Join Date
    Oct 2011
    Posts
    65
    Rep Power
    0

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    int value can not contain 30 digit number so you can not put value into int

  11. #11
    Zora is offline Member
    Join Date
    Sep 2011
    Posts
    21
    Rep Power
    0

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Whoa I didn't expect to see the full written code! It's amazing how things like BigInteger, BigSum, etc...can save a lot of time. Though, I shouldn't use this unless I understand how it works, so I need some clarification.

    Could you explain these segments in a bit more detail:

    Java Code:
    String max_len = (strInput1.length() > strInput2.length()) ? strInput1 : strInput2;
    String min_len = (strInput1.length() > strInput2.length()) ? strInput2 : strInput1;
    
    
    if(digits1.length > digits2.length) {
                digits3 = new String[digits1.length];
                for(int i = 0; i < digits3.length; i++) {
                    digits3[i] = "0";
                }
                int iCount = digits3.length;
                for(int j = (digits2.length - 1); j >= 0 ; j--) {
                    digits3[--iCount] = digits2[j];
                }
            }
    
    
    if(digits1.length > digits2.length)
                    low = Integer.parseInt(digits3[index]);
                else
                    low = Integer.parseInt(digits2[index]);
    I've never used parseInt before. I'm also in the middle of modifying your code into methods and arrays, since that's what I'm supposed to use.

  12. #12
    rajkapur is offline Member
    Join Date
    Nov 2011
    Location
    india
    Posts
    1
    Rep Power
    0

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Why prefer console in place scanner;

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Quote Originally Posted by rajkapur View Post
    Why prefer console in place scanner;
    Do you mean in Eranga's code?

    He *was* using Scanner rather than Console. He used the variable console as this is a common way of referring to a something (input stream, reader, scanner, etc) that depends ultimately on System.in.

  14. #14
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    First of all, sorry for the late reply.

    Quote Originally Posted by Zora View Post
    Whoa I didn't expect to see the full written code! It's amazing how things like BigInteger, BigSum, etc...can save a lot of time. Though, I shouldn't use this unless I understand how it works, so I need some clarification.
    Normally I didn't do this, just pasting the full code relevant to OPs' question. Actually I really hate it. However, your question title gives an impression to give a try.

    Quote Originally Posted by Zora View Post
    Could you explain these segments in a bit more detail:
    Of course.

    Java Code:
    String max_len = (strInput1.length() > strInput2.length()) ? strInput1 : strInput2;
    String min_len = (strInput1.length() > strInput2.length()) ? strInput2 : strInput1;
    As you seen, I have stored digits of two user entered numbers in two separate arrays. So I can process digits, rather dealing with the whole number, which is quite difficult. Then in the above code segment I identified which number (actually the array with digits) is the longest (not the largest). Reason is, which ever the order that user entered the two numbers, I want to use the same logic.

    Java Code:
    if(digits1.length > digits2.length) {
                digits3 = new String[digits1.length];
                for(int i = 0; i < digits3.length; i++) {
                    digits3[i] = "0";
                }
                int iCount = digits3.length;
                for(int j = (digits2.length - 1); j >= 0 ; j--) {
                    digits3[--iCount] = digits2[j];
                }
            }

    Once I found the longest and shortest numbers, arrange them as follows

    XXXXXXXX --> Longest number
    XXXXX --> Shortest number
    So you can see on left-most digits there is a mismatch, and it is not possible to simple add the corresponding digits from both numbers after a certain. So fill with zeros.

    XXXXXXXX --> Longest number
    000XXXXX --> Shortest number
    Then you can simple add relevant starting from right-most digit. Still you are not clear with something let me know.

  15. #15
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,371
    Blog Entries
    1
    Rep Power
    20

    Default Re: Summing 2 Integers Together (not as easy as it sounds)

    Quote Originally Posted by rajkapur View Post
    Why prefer console in place scanner;
    You got the best explanation from pbrockway2s' post.

Similar Threads

  1. Java: summing up array elements and displaying
    By dambundos in forum New To Java
    Replies: 7
    Last Post: 10-22-2011, 03:34 PM
  2. Summing a Series: Is this correct??
    By son012189 in forum New To Java
    Replies: 4
    Last Post: 10-05-2011, 06:36 PM
  3. Summing the digit
    By gozuhair in forum New To Java
    Replies: 13
    Last Post: 07-18-2011, 08:09 AM
  4. summing value within Hashtable
    By dc0m in forum New To Java
    Replies: 4
    Last Post: 09-23-2010, 01:17 AM
  5. Help with summing series
    By xplsivo in forum New To Java
    Replies: 8
    Last Post: 11-23-2009, 08:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •