[Solved] Find Remainder without using Modulus Operator in Python, C and Java?

[Solved] Find Remainder without using Modulus Operator in Python, C and Java?

The remainder is the value remains after dividing one number by another number.

Example 1:

Number: 8 Divisor: 3
Reminder: 2

Example 2:

Number: 33 Divisor: 4
Reminder: 1

There are some special cases.

  • If the number is zero, the remainder is zero irrespective of the divider.
  • If the number and divisor are the same, the remainder is zero.
  • The divisor can not be zero. Dividing any number by zero is an invalid arithmetic operation. And most of the programming languages throws an exception.

In most of the programming languages, we can find the remainder with a simple modulo operator (%).

Remainder using Modulo Operator:

10%3  = 1
23%5 = 3

Now, our task is to find a reminder without using the modulo operator.

Problem Statement:

Write an Algorithm and Program to Find Remainder without using Modulus Operator.

We are using the subtraction mathematical operator to find the reminder.

Algorithm

If the number (num) is zero0, return zero.
If the divisor (d) is zero, return -1 (invalid operation)
while number(num) is greater than or equal to divisor (d)
- num=num-d
return num

Python Program

def reminder(num, d):
  if num==0:
    return 0
  elif d==0:
    return -1
  while num>=d:
    num = num-d
  return num

print(reminder(34, 3)) 

Output:

4

C/C++ Program

int reminder(int num, int d)
{
  if(num==0)
    return 0;
  else if(d==0)
    return -1;
  while(num>=d)
    num = num-d;
  return num;
}

void main()
{
  int out = reminder(26, 3);
  printf("%d", out);
}

Output:

2

Java Program

public class MyClass {
  static int reminder(int num ,int d) {
    if(num==0)
      return 0;
    else if(d==0)
      return -1;
    while(num>=d)
      num = num-d;
    return num;
  }

  public static void main(String[] args) {
    int out= reminder(24, 7);
    System.out.println(out);
  }
}

Output:

3

This coding question was asked in the OVH cloud technical interview round.

If you want to excel in programming or if you are preparing for an IT job, keep practice solving interview coding questions.

Leave a Reply

Your email address will not be published. Required fields are marked *