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.
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:
We are using the subtraction mathematical operator to find the reminder.
Table of Contents
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
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
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
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.