multiply two numbers <=10^18 %m in cpp
#include <iostream>
using namespace std;
const long long MOD = 1000000007;
long long multiply(long long a, long long b) {
a %= MOD;
b %= MOD;
return (a * b) % MOD;
}
int main() {
long long num1, num2;
cin >> num1 >> num2;
long long result = multiply(num1, num2);
cout << result << endl;
return 0;
}
Explanation:
- The code starts with including the necessary libraries, "iostream" in this case, which provides input and output stream objects such as cin
and cout
.
- The using namespace std;
statement allows us to use the standard library elements without specifying the namespace every time.
- Next, a constant variable MOD
is declared and initialized with the value 1000000007. This value is used for modulo arithmetic later in the code.
- The multiply
function takes two long long
arguments, a
and b
, which represent the numbers to be multiplied. It returns the product of a
and b
modulo MOD
.
- Inside the multiply
function, the values of a
and b
are reduced modulo MOD
using the %
operator, which ensures that the result is within the range of MOD
.
- The product of a
and b
modulo MOD
is then calculated using the *
operator and the %
operator again.
- In the main
function, two long long
variables num1
and num2
are declared.
- The values of num1
and num2
are read from the standard input using the cin
object.
- The multiply
function is called with num1
and num2
as arguments, and the result is stored in the result
variable.
- Finally, the value of result
is printed to the standard output using the cout
object, followed by an endline character.
- The return 0;
statement indicates successful termination of the program.