Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

C: String arithmetic without Bignum library

c strings

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 negru

negru

    CC Newcomer

  • Member
  • PipPip
  • 17 posts

Posted 13 January 2016 - 03:42 AM

Write a program (without using GMP library - https://gmplib.org) which performs arithmetic operations on large positive integers (addition, subtraction, multiplication and division). Maximum number of digits in one number is 100.

Large number is the number that can't be represented by standard data types (long long, ...), and it is represented as a string.

Then allow incrementing and decrementing of a string, and finding the smallest and the largest string in an array of n strings.

 

How would you do incrementing, decrementing and comparing Bignum strings?

Here is the addition:

    #include<stdio.h>
    #define MAX 100//max. number of digits
    typedef struct
    {
        int arr[MAX];//array for one number
    }NUMBER;
    void read(NUMBER *add_num)//read one number
    {
        int i,digit=0;
        char ch[101];
        scanf("%s",ch);

        while(ch[digit])//number of digits
            digit++;

        for(i=0;i < MAX;i++)
        {
            digit--;
            if(digit >= 0)
                add_num->arr[i]=ch[digit]-'0';//int to char
            else
                add_num->arr[i]=0;
        }
    }

    void addition(NUMBER a,NUMBER b,NUMBER *add_res)//add two Bignum strings
    {
        int carry=0;
        int i,temp;
        for(i=0;i < MAX;i++)
        {
            temp=a.arr[i]+b.arr[i]+carry;//sum
            add_res->arr[i]=temp % 10;//resulting digit
            carry=temp / 10;//store carry
        }
    }

    void print(NUMBER *add_num)//print result
    {
        int i;

        for(i=MAX-1;add_num->arr[i]==0;i--);//skip the leading zeros

        for(;i>=0;i--)
            printf("%d",add_num->arr[i]);
    }
    int main()
    {
        NUMBER x,y,z;
        printf("enter two positive integers: \n");
        read(&x);
        read(&y);
        printf("addition result: ");
        addition(x,y,&z);
        print(&z);
        return 0;
    }


#2 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts

Posted 13 January 2016 - 08:38 PM

Your addition should be going from right to left, i.e. for( i = MAX - 1; i > 0; --i ) {...}.


sudo rm -rf / && echo $'Sanitize your inputs!'