Sunday, October 12, 2025
HomeData Modelling & AIProduct of all numbers up to N that are co-prime with N

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:

  1. Initialize the product as 1.
  2. Iterate over the range [1, N] and if GCD of i and N is 1, multiply product with i.
  3. 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 b
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 N
int 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 Code
int main()
{
    int N = 5;
 
    cout << findProduct(N);
    return 0;
}


Java




// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Function to return
// gcd of a and b
static 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 N
static 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 Code
public 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 b
def 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 N
def 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 Code
if __name__ == '__main__':
   
    N = 5;
    print(findProduct(N));
 
# This code is contributed by 29AjayKumar


C#




// C# program for the
// above approach
using System;
 
class GFG{
 
// Function to return
// gcd of a and b
static 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 N
static 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 Code
public 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 b
function 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 N
function 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 Code
var N = 5;
document.write(findProduct(N))
 
</script>


Output

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 Function
int 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 N
int 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 = 5
print(co_prime_product_3(N))


Output

24

Time Complexity: O(N log N)
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32353 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6721 POSTS0 COMMENTS
Nicole Veronica
11885 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11943 POSTS0 COMMENTS
Shaida Kate Naidoo
6841 POSTS0 COMMENTS
Ted Musemwa
7105 POSTS0 COMMENTS
Thapelo Manthata
6797 POSTS0 COMMENTS
Umr Jansen
6798 POSTS0 COMMENTS