Given two positive integers a and b, find the product of the two numbers on a 12-hour clock rather than a number line.
Note:Â Assume the Clock starts from 0 hours to 11 hours.
Examples:
Input: a = 2, b = 3
Output: 6
Explanation: 2*3 = 6. The time in a 12 hour clock is 6.Input: a = 3, b = 5
Output: 3
Explanation: 3*5 = 15. The time in a 12 hour clock is 3.
[Expected Approach] Modular Multiplication - O(1) Time and O(1) Space
The idea is to reduce both numbers modulo 12 before multiplication. This avoids overflow for large values and gives the same result because (a * b) % 12 = ((a % 12) * (b % 12)) % 12.
#include <iostream>
using namespace std;
int mulClock(int a, int b) {
// Reduce both numbers first to avoid overflow.
return (a % 12) * (b % 12) % 12;
}
int main() {
cout << mulClock(2, 3) << endl;
cout << mulClock(3, 5) << endl;
return 0;
}
class GFG {
static int mulClock(int a, int b) {
// Reduce both numbers first to avoid overflow.
return (a % 12) * (b % 12) % 12;
}
public static void main(String[] args) {
System.out.println(mulClock(2, 3));
System.out.println(mulClock(3, 5));
}
}
def mulClock(a, b):
# Reduce both numbers first to avoid overflow.
return (a % 12) * (b % 12) % 12
if __name__ == "__main__":
print(mulClock(2, 3))
print(mulClock(3, 5))
using System;
class GFG {
static int mulClock(int a, int b) {
// Reduce both numbers first to avoid overflow.
return (a % 12) * (b % 12) % 12;
}
static void Main() {
Console.WriteLine(mulClock(2, 3));
Console.WriteLine(mulClock(3, 5));
}
}
function mulClock(a, b) {
// Reduce both numbers first to avoid overflow.
return ((a % 12) * (b % 12)) % 12;
}
// Driver Code
console.log(mulClock(2, 3));
console.log(mulClock(3, 5));
Output
6 3