Product of all numbers up to N that are co-prime with N

Given an integer N, the task is to find the product of all the numbers from the range [1, N] that are co-prime to the given number N.
Examples:
Input: N = 5
Output: 24
Explanation:
Numbers which are co-prime with 5 are {1, 2, 3, 4}.
Therefore, the product is given by 1 * 2 * 3 * 4 = 24.Input: N = 6
Output: 5
Explanation:
Numbers which are co-prime to 6 are {1, 5}.
Therefore, the required product is equal to 1 * 5 = 5
Approach: The idea is to iterate over the range [1, N] and for every number, check if its GCD with N is equal to 1 or not. If found to be true for any number, then include that number in the resultant product.Â
Follow the steps below to solve the problem:
- Initialize the product as 1.
- Iterate over the range [1, N] and if GCD of i and N is 1, multiply product with i.
- After the above step, print the value of the product.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <iostream>using namespace std;Â
// Function to return gcd of a and bint gcd(int a, int b){    // Base Case    if (a == 0)        return b;Â
    // Recursive GCD    return gcd(b % a, a);}Â
// Function to find the product of// all the numbers till N that are// relatively prime to Nint findProduct(unsigned int N){    // Stores the resultant product    unsigned int result = 1;Â
    // Iterate over [2, N]    for (int i = 2; i < N; i++) {Â
        // If gcd is 1, then find the        // product with result        if (gcd(i, N) == 1) {            result *= i;        }Â
            }   // Return the final product        return result;}Â
// Driver Codeint main(){Â Â Â Â int N = 5;Â
    cout << findProduct(N);    return 0;} |
Java
// Java program for the // above approachimport java.util.*;class GFG{Â
// Function to return // gcd of a and bstatic int gcd(int a, int b){  // Base Case  if (a == 0)    return b;Â
  // Recursive GCD  return gcd(b % a, a);}Â
// Function to find the // product of all the // numbers till N that are// relatively prime to Nstatic int findProduct(int N){  // Stores the resultant   // product  int result = 1;Â
  // Iterate over [2, N]  for (int i = 2; i < N; i++)   {    // If gcd is 1, then     // find the product     // with result    if (gcd(i, N) == 1)     {      result *= i;    }  }     // Return the final   // product  return result;}Â
// Driver Codepublic static void main(String[] args){Â Â int N = 5;Â Â System.out.print(findProduct(N));}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 program for the# above approachÂ
# Function to return# gcd of a and bdef gcd(a, b):       # Base Case    if (a == 0):        return b;Â
    # Recursive GCD    return gcd(b % a, a);Â
# Function to find the# product of all the# numbers till N that are# relatively prime to Ndef findProduct(N):       # Stores the resultant    # product    result = 1;Â
    # Iterate over [2, N]    for i in range(2, N):               # If gcd is 1, then        # find the product        # with result        if (gcd(i, N) == 1):            result *= i;Â
    # Return the final    # product    return result;Â
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â N = 5;Â Â Â Â print(findProduct(N));Â
# This code is contributed by 29AjayKumar |
C#
// C# program for the // above approachusing System;Â
class GFG{Â
// Function to return // gcd of a and bstatic int gcd(int a, int b){     // Base Case  if (a == 0)    return b;Â
  // Recursive GCD  return gcd(b % a, a);}Â
// Function to find the // product of all the // numbers till N that are// relatively prime to Nstatic int findProduct(int N){     // Stores the resultant   // product  int result = 1;Â
  // Iterate over [2, N]  for(int i = 2; i < N; i++)   {         // If gcd is 1, then     // find the product     // with result    if (gcd(i, N) == 1)     {      result *= i;    }  }     // Return the readonly   // product  return result;}Â
// Driver Codepublic static void Main(String[] args){Â Â int N = 5;Â Â Â Â Â Console.Write(findProduct(N));}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>Â
Â
// Javascript program for the above approachÂ
// Function to return gcd of a and bfunction gcd(a, b){    // Base Case    if (a == 0)        return b;Â
    // Recursive GCD    return gcd(b % a, a);}Â
// Function to find the product of// all the numbers till N that are// relatively prime to Nfunction findProduct( N){    // Stores the resultant product    var result = 1;Â
    // Iterate over [2, N]    for (var i = 2; i < N; i++) {Â
        // If gcd is 1, then find the        // product with result        if (gcd(i, N) == 1) {            result *= i;        }            }   // Return the final product        return result;}Â
// Driver Codevar N = 5;document.write(findProduct(N))Â
</script> |
24
Time Complexity: O(N log N)
Auxiliary Space: O(1)
Approach#2: Using nested while
This approach calculates the product of all numbers up to N that are co-prime with N, using Euler’s totient function. It first factorizes N and then applies the formula for Euler’s totient function to compute the product.
Algorithm
1. Find the Euler totient function value of N, which gives the count of numbers that are co-prime to N.
2. Calculate the product of all integers up to N-1.
C++
#include <iostream>using namespace std;Â
int main() {Â
    cout << "GFG!";    return 0;} |
C++
#include <iostream>#include <cmath>Â
// Function to calculate the greatest common divisor (GCD)int gcd(int a, int b) {Â Â Â Â if (b == 0) {Â Â Â Â Â Â Â Â return a;Â Â Â Â }Â Â Â Â return gcd(b, a % b);}Â
// Function to calculate Euler's Totient Functionint eulerTotient(int n) {    int phi = n; // Initialize phi with the value of n    int i = 2;    while (i * i <= n) {        if (n % i == 0) {            while (n % i == 0) {                n /= i; // Reduce n by its prime factors            }            phi -= phi / i; // Update phi using Euler's Totient formula        }        i++;    }    if (n > 1) {        phi -= phi / n; // If there is one more prime factor remaining    }    return phi;}Â
// Function to calculate the product of co-prime numbers with Nint coPrimeProduct(int N) {    int phi_N = eulerTotient(N); // Calculate Euler's Totient for N    int product = 1; // Initialize the product as 1    for (int i = 1; i < N; i++) {        if (gcd(i, N) == 1) { // Check if i is co-prime with N using GCD            product *= i; // Multiply i to the product if it's co-prime        }    }    return product;}Â
int main() {    int N = 5;    int result = coPrimeProduct(N); // Calculate the co-prime product for N    std::cout << result << std::endl; // Print the result    return 0;} |
Python3
from math import gcdÂ
def co_prime_product_3(N):    def euler_totient(n):        phi = n        i = 2        while i*i <= n:            if n % i == 0:                while n % i == 0:                    n //= i                phi -= phi // i            i += 1        if n > 1:            phi -= phi // n        return phi         phi_N = euler_totient(N)    product = 1    for i in range(1, N):        if gcd(i, N) == 1:            product *= i    return productÂ
N = 5print(co_prime_product_3(N)) |
24
Time Complexity: O(N log N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



