user478571
user478571

Reputation:

array comparison for multiplication & subtraction

I have two big numbers (type int) which are stored in array with a size at least 1000, and I want to compare these two numbers to get information which one is bigger than the other. How can I do this?

Actually , I will do two things

  1. subtract these two
  2. multiply these two (I am studying in this topic, indeed, and I didn't find an efficient algorithm; feel free to help me)

Upvotes: 1

Views: 766

Answers (5)

Jim Fell
Jim Fell

Reputation: 14256

int iArray[1000] = { /* ... */ };

int Subtract( int idx1, int idx2 )
{
    return iArray[idx1] - iArray[idx2];
}

// Return data type size is increased to prevent overflow.
long Multiply( int idx1, int idx2 )
{
    return (long)iArray[idx1] * (long)iArray[idx2];
}

int Compare( int idx1, int idx2 )
{
    if ( iArray[idx1] > iArray[idx2] )
    {
        return 1; // Value at index 1 is greater than value at index 2.
    }
    else if ( iArray[idx1] < iArray[idx2] )
    {
        return -1; // Value at index 1 is less than value at index 2.
    }
    else
    {
        return 0; // Values at both indexes are equal.
    }
}

Upvotes: 0

AsifQadri
AsifQadri

Reputation: 2388

Suppose you have an integer array

int Marks[1000]={22,32,12,..............};

First of all you sort your array

int g,r,c;
for ( r=0; r <=999; r++)
   {
     for ( g=r+1;g<=1000;g++)
        {
            if ( Marks[r]  < Marks[g] )
               {
                   c=Marks[r];                // these 3 statements swap values
                   Marks[r] =Marks[g];          // in the 2 cells being compared  
                   Marks[g] = c;
                }
        }   
   } 

Now you find that largest number is Marks[0] and second large is Marks[1]

Upvotes: 2

MAK
MAK

Reputation: 26586

Make sure your arrays have no leading zeros. Now, if they are not the same size, the larger array has to be holding a bigger value (for the same reason 1000 is bigger than 10). Otherwise, just compare them as you would compare strings (i.e. starting from the most significant digit).

Upvotes: 2

Flinsch
Flinsch

Reputation: 4341

  1. Compare lengths: The larger array represents the bigger number.
  2. If equal sizes: digit-wise comparison until not identical.

Upvotes: 2

Beno&#238;t
Beno&#238;t

Reputation: 7427

It will depend on the coding of your big nnumber in the array !

Upvotes: 2

Related Questions