Home > Blockchain >  How to run a c program using loops to find the remainder of two numbers without using multiplication
How to run a c program using loops to find the remainder of two numbers without using multiplication

Time:11-18

#include <stdio.h>

int main()
{
    int num1, num2;

    printf ("Input value for num1: ");
    scanf ("%d", &num1);
    printf ("Input value for num2: ");
    scanf ("%d", &num2);   

    int prod =0, i;
    for(i = 1; i <= num1; i  ){
        prod  = num2;
    }

    int quo = 0 , rem = 0;
    for(rem = num1 - num2; rem >= 0; rem = rem-num2) {
        if(rem < 0)             
            break;
        else
            quo  ;
    }

    //The last part is that i need to find the remainder without  using multiplication, division and the modulo itself.

    printf ("The product of %d and %d is: %d\n", num1, num2, prod);
    printf ("The integer quotient of %d and %d is: %d\n", num1, num2, quo);

    return 0;
}

CodePudding user response:

The simplest solution for calculating a mod b for positive integers a and b with only subtraction and addition is to subtract b from a until the result is smaller than a. However, this takes many iterations if b is much smaller than a.

A method with better worst-case performance is the following:

#include <stdio.h>

unsigned rem(unsigned a, unsigned b)
{
    if(b == 0) return 0;  // Error
    while(a >= b)
    {
        unsigned s = b;
        do
        {
            a = a - s;
            s = s   s;
        } while(a >= s);
    }
    return a;
}

int main(void)
{
    unsigned example = rem(32453, 3);
    printf("%u\n", example);
}

This method is based on the fact that to get closer to the result, we can subtract any multiple of b as long as it is smaller than a, so in each inner iteration we try to subtract twice the multiples of the last iteration until the subtractor becomes too large and we start over again with a single multiple of b.

Be aware that this will give wrong results if s = s s; overflows the unsigned range. Hence, a should not be larger than half the upper limit of unsigned.

CodePudding user response:

If you want a slow calculation of num1 % num2 (i.e. without multiplication/division) you can do:

// Calculate num1 % num2

unsigned rem(unsigned num1, unsigned num2)
{
    if (num2 == 0) {.... error handling ....}

    while (num1 >= num2) num1 -= num2;
    return num1;
}

int main(void)
{
    unsigned num1 = 42;
    unsigned num1 = 3;
    unsigned rem = rem(num1, num2);
    printf("%u", rem);
    return 0;
}
  • Related