Open In App

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

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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;
}


Java




public class Main {
 
    // Function to calculate the greatest common divisor (GCD)
    static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
 
    // Function to calculate Euler's Totient Function
    static 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
    static 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;
    }
 
    public static void main(String[] args) {
        int N = 5;
        int result = coPrimeProduct(N); // Calculate the co-prime product for N
        System.out.println(result); // Print the result
    }
}


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))


C#




using System;
 
class MainClass {
    // Function to calculate the greatest common divisor
    // (GCD)
    static int Gcd(int a, int b)
    {
        if (b == 0) {
            return a;
        }
        return Gcd(b, a % b);
    }
 
    // Function to calculate Euler's Totient Function
    static 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
    static int CoPrimeProduct(int 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;
    }
 
    public static void Main(string[] args)
    {
        int N = 5;
        int result = CoPrimeProduct(
            N); // Calculate the co-prime product for N
        Console.WriteLine("Co-Prime Product for N = " + N
                          + ": "
                          + result); // Print the result
    }
}


Javascript




// Function to calculate the greatest common divisor (GCD)
function gcd(a, b) {
    if (b === 0) {
        return a;
    }
    return gcd(b, a % b);
}
 
// Function to calculate Euler's Totient Function
function eulerTotient(n) {
    let phi = n; // Initialize phi with the value of n
    let i = 2;
    while (i * i <= n) {
        if (n % i === 0) {
            while (n % i === 0) {
                n /= i; // Reduce n by its prime factors
            }
            phi -= Math.floor(phi / i); // Update phi using Euler's Totient formula
        }
        i++;
    }
    if (n > 1) {
        phi -= Math.floor(phi / n); // If there is one more prime factor remaining
    }
    return phi;
}
 
// Function to calculate the product of co-prime numbers with N
function coPrimeProduct(N) {
    let phi_N = eulerTotient(N); // Calculate Euler's Totient for N
    let product = 1; // Initialize the product as 1
    for (let 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;
}
 
// Main function
function main() {
    let N = 5;
    let result = coPrimeProduct(N); // Calculate the co-prime product for N
    console.log(result); // Print the result
}
 
// Invoke the main function
main();


Output

24





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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads