Thread: subtraction of arbitrary big number

  1. #1
    Registered User
    Join Date
    Sep 2016
    Posts
    1

    subtraction of arbitrary big number

    Code:
    /* * used to add two numbers with the same sign
     * GIVEN FOR GUIDANCE
     */
    int* add(int* input1, int* input2, int base) { 
    	int len1 = bignum_length(input1);   //get length of first input
    	int len2 = bignum_length(input2);   //get length of second input
    	int resultlength = ((len1 > len2)? len1 : len2) + 2;  //if len1 > len2, return len1, if len2 > len1, return len 2. Then add 2 to the result
    	int* result = (int*) malloc (sizeof(int) * resultlength);  //allocate a memeory address of the size of int x resultlength
    	int r = 0;   //index
    	int carry = 0;   //carry over
    	int sign = input1[len1];  //last element of input1, which is -1
        	int num1, num2;
    
    
    	len1--;
    	len2--;
    
    
    	while (len1 >= 0 || len2 >= 0) {
            if (len1 >= 0) {
                num1 = input1[len1];
            } else {
                num1 = 0;
            }
    
    
            if (len2 >= 0) {
                num2 = input2[len2];
            } else {
                num2 = 0;
            }
    		result[r] = (num1 + num2 + carry) % base;
    		carry = (num1 + num2 + carry) / base;
    		len1--;
    		len2--;
    		r++;
    	}
    	if (carry > 0) {
            result[r] = carry; 
            r++; 
        }
    	result[r] = sign;
    	reverse(result);
    	return result;
    }
    how can i write a subtraction method base on this add method?
    or can someone explain what each line of this method code do?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Write out the steps for this calculation by hand on a piece of paper.
    103
    017 -
    ---


    When you know what 'borrow' means, and how it relates to 'carry' when doing addition, you'll be able to write the code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Subtraction in C
    By Satya in forum C Programming
    Replies: 1
    Last Post: 02-23-2015, 11:36 AM
  2. pointer subtraction
    By bhrugu in forum C Programming
    Replies: 10
    Last Post: 08-07-2010, 02:04 PM
  3. help! calculate arbitrary number of floating points
    By cakestler in forum C Programming
    Replies: 5
    Last Post: 02-26-2009, 02:47 PM
  4. Division By Subtraction
    By blacksnake in forum C++ Programming
    Replies: 19
    Last Post: 01-13-2007, 10:17 AM
  5. Comparison by subtraction
    By Thantos in forum C++ Programming
    Replies: 13
    Last Post: 10-05-2004, 08:24 PM

Tags for this Thread