Number Theory and Binary Search
Description
- Topics : Number Theory, Binary Search
- Link to the contest
Editorial
caution
Don’t read the editorial, if you have not attempted or read the problems. It would hamper your thinking capability, if you do so.
A. Find mod m
- Problem
- Editorial
- Code
Given 3 positive integers - , and . Find value of mod .
The function is defined as the product of square of primes up to (inclusive).
For eg. .
Constraints
Since , we need to use sieve of Erasthoneses to find out all the prime numbers from 1 to in .
Also, one could easily observe that the value of would definitely overflow for larger values of . So, we can't find directly.
Here, we can use the property . For finding , use binary exponentation, which works in .
Final time complexity:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MAX = 1e6;
int modulo(int a, int b, int n) {
// Binar exponentation to calculate a^b in O(log b)
int x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y) % n;
}
y = (y * y) % n;
b /= 2;
}
return x % n;
}
int32_t main() {
int x, n, m;
cin >> x >> n >> m;
sieve(); // pre-compute all the primes
int prod = x; // final answer would be stored in prod
for (int i = 2; i <= n; i++) {
if (is_prime[i]) {
prod = modulo(prod, i, m);
prod = modulo(prod, i, m);
// Use the property (a^b)^c = a^(b*c).
// Since, directly calculating F(n) first will overflow
}
}
cout << prod;
return 0;
}