[Geeks for Geeks] Product of Primes

Product of Primes

Given two numbers L and R (inclusive) find the product of primes within this range. Print the product modulo 109+7. If there are no primes in that range you must print 1.

  • Time : O((r-l)sqrt(r))
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution{
long long mod = 1e9 + 7;
bool isPrime(long long n) {
for(long long i = 2; i * i <= n; i++)
if(n % i == 0) return false;
return true;
}
public:
long long primeProduct(long long L, long long R){
long long res = 1;
for(long long i = L; i <= R; i++) {
if(!(i & 1)) continue;
if(isPrime(i)) res = (res * i) % mod;
}
if(L <= 2 and 2 <= R) res *= 2;
return res % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/product-of-primes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.