Sum of all numbers up to N that are co-prime with N
Last Updated :
03 May, 2024
Given an integer N, the task is to find the sum of all numbers in the range [1, N] that are co-prime with the given number N.
Examples:
Input: N = 5
Output: 10
Explanation:
Numbers which are co-prime with 5 are {1, 2, 3, 4}.
Therefore, the sum is given by 1 + 2 + 3 + 4 = 10.
Input: N = 6
Output: 5
Explanation:
Numbers which are co-prime to 6 are {1, 5}.
Therefore, the required sum is equal to 1 + 5 = 6
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 sum. Follow the steps below to solve the problem:
- Initialize the sum as 0.
- Iterate over the range [1, N] and if GCD of i and N is 1, add i to sum.
- After completing the above steps, print the value of the sum obtained.
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 calculate the sum of all
// numbers till N that are coprime with N
int findSum(unsigned int N)
{
// Stores the resultant sum
unsigned int sum = 0;
// Iterate over [1, N]
for (int i = 1; i < N; i++) {
// If gcd is 1
if (gcd(i, N) == 1) {
// Update sum
sum += i;
}
}
// Return the final sum
return sum;
}
// Driver Code
int main()
{
// Given N
int N = 5;
// Function Call
cout << findSum(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 calculate the
// sum of all numbers till N
// that are coprime with N
static int findSum(int N)
{
// Stores the resultant sum
int sum = 0;
// Iterate over [1, N]
for (int i = 1; i < N; i++)
{
// If gcd is 1
if (gcd(i, N) == 1)
{
// Update sum
sum += i;
}
}
// Return the final sum
return sum;
}
// Driver Code
public static void main(String[] args)
{
// Given N
int N = 5;
// Function Call
System.out.print(findSum(N));
}
}
// This code is contributed by gauravrajput1
Python
# Python 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 calculate the
# sum of all numbers till N
# that are coprime with N
def findSum(N):
# Stores the resultant sum
sum = 0;
# Iterate over [1, N]
for i in range(1, N):
# If gcd is 1
if (gcd(i, N) == 1):
# Update sum
sum += i;
# Return the final sum
return sum;
# Driver Code
if __name__ == '__main__':
# Given N
N = 5;
# Function Call
print(findSum(N));
# This code is contributed by Rajput-Ji
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 calculate the
// sum of all numbers till N
// that are coprime with N
static int findSum(int N)
{
// Stores the resultant sum
int sum = 0;
// Iterate over [1, N]
for (int i = 1; i < N; i++)
{
// If gcd is 1
if (gcd(i, N) == 1)
{
// Update sum
sum += i;
}
}
// Return the readonly sum
return sum;
}
// Driver Code
public static void Main(String[] args)
{
// Given N
int N = 5;
// Function Call
Console.Write(findSum(N));
}
}
// This code is contributed by shikhasingrajput
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 calculate the sum of all
// numbers till N that are coprime with N
function findSum(N)
{
// Stores the resultant sum
var sum = 0;
// Iterate over [1, N]
for (var i = 1; i < N; i++) {
// If gcd is 1
if (gcd(i, N) == 1) {
// Update sum
sum += i;
}
}
// Return the final sum
return sum;
}
// Driver Code
// Given N
var N = 5;
// Function Call
document.write(findSum(N));
</script>
Time Complexity: O(N*log2(N)), as here we iterate loop from i=1 to N and for every i we calculate gcd(i,N) which takes log2(N) time so overall time complexity will be O(N*log2(N)) (for doing gcd of two number a&b we need time log2(max(a,b)), here among i and N, N is the maximum number so log2(N) for gcd)
Auxiliary Space: O(1)
Efficient Summation Using Euler’s Totient Function
This approach utilizes Euler’s Totient Function (φ(N)), which counts the number of integers up to N that are coprime with N. Instead of calculating the GCD for each number up to N, we compute the values that are coprime using the properties of the Euler’s Totient function, then sum them directly.
Follow the steps to solve the problem:
- Precompute values using Euler’s Totient function to identify numbers that are coprime with N.
- Utilize a modified Sieve of Eratosthenes to efficiently compute the φ values for all numbers up to N.
- Sum only the values which are coprime with N based on the φ function result, improving efficiency compared to computing GCD repeatedly.
Below is the implementation of above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to compute the sum of numbers that are coprime
// to N
int sum_coprimes(int N)
{
if (N == 1) {
return 1; // The only coprime with 1 is itself
}
// Vector to store the Euler's Totient function values
// for each number up to N
vector<int> phi(N + 1);
for (int i = 0; i <= N; ++i) {
phi[i] = i; // Initialize phi with itself
}
// Using a modified Sieve to calculate phi values
for (int p = 2; p <= N; ++p) {
if (phi[p] == p) { // Check if p is a prime
for (int k = p; k <= N; k += p) {
phi[k] *= (p - 1);
phi[k] /= p;
}
}
}
// Calculate the sum of numbers that are coprime to N
int sum_coprimes = 0;
for (int i = 1; i <= N; ++i) {
if (phi[i] == i - 1) { // If i is coprime with N,
// add it to the sum
sum_coprimes += i;
}
}
return sum_coprimes;
}
// Main function to demonstrate the functionality of
// sum_coprimes
int main()
{
int N = 5;
cout << sum_coprimes(N) << endl;
return 0;
}
Java
import java.util.*;
public class SumCoprimes {
// Function to compute the sum of numbers that are
// coprime to N
public static int sumCoprimes(int N)
{
if (N == 1) {
return 1; // The only coprime with 1 is itself
}
// Array to store the Euler's Totient function
// values for each number up to N
int[] phi = new int[N + 1];
for (int i = 0; i <= N; ++i) {
phi[i] = i; // Initialize phi with itself
}
// Using a modified Sieve to calculate phi values
for (int p = 2; p <= N; ++p) {
if (phi[p] == p) { // Check if p is a prime
for (int k = p; k <= N; k += p) {
phi[k] *= (p - 1);
phi[k] /= p;
}
}
}
// Calculate the sum of numbers that are coprime to
// N
int sumCoprimes = 0;
for (int i = 1; i <= N; ++i) {
if (phi[i] == i - 1) { // If i is coprime with
// N, add it to the sum
sumCoprimes += i;
}
}
return sumCoprimes;
}
// Main function to demonstrate the functionality of
// sumCoprimes
public static void main(String[] args)
{
int N = 5;
System.out.println(sumCoprimes(N));
}
}
Python
def sum_coprimes(N):
if N == 1:
return 1 # The only coprime with 1 is itself
# Using a modified Sieve to calculate Euler's Totient function for all numbers up to N
phi = list(range(N + 1))
for p in range(2, N + 1):
if phi[p] == p: # p is a prime
for k in range(p, N + 1, p):
phi[k] *= (p - 1)
phi[k] //= p
# Calculate the sum of coprimes by summing values where gcd(i, N) == 1
sum_coprimes = sum(i for i in range(1, N + 1) if phi[i] == i - 1)
return sum_coprimes
# Example usage
N = 5
print(sum_coprimes(N)) # Output: 10
JavaScript
// Function to compute the sum of numbers that are coprime to N
function sumCoprimes(N) {
if (N === 1) {
return 1; // The only coprime with 1 is itself
}
// Array to store the Euler's Totient function values for each number up to N
const phi = new Array(N + 1);
for (let i = 0; i <= N; ++i) {
phi[i] = i; // Initialize phi with itself
}
// Using a modified Sieve to calculate phi values
for (let p = 2; p <= N; ++p) {
if (phi[p] === p) { // Check if p is a prime
for (let k = p; k <= N; k += p) {
phi[k] *= (p - 1);
phi[k] /= p;
}
}
}
// Calculate the sum of numbers that are coprime to N
let sumCoprimes = 0;
for (let i = 1; i <= N; ++i) {
if (phi[i] === i - 1) { // If i is coprime with N, add it to the sum
sumCoprimes += i;
}
}
return sumCoprimes;
}
// Main function to demonstrate the functionality of sumCoprimes
function main() {
const N = 5;
console.log(sumCoprimes(N));
}
main();
Time Complexity: O(NloglogN). The use of the sieve-like approach for computing Euler’s Totient function for all numbers up to N optimizes the time complexity compared to direct GCD calculations for each number.
Auxilary Space: O(N). The space complexity is primarily due to the storage required for the phi array, which holds the totient values for all integers up to N.
Share your thoughts in the comments
Please Login to comment...