Sum of all numbers up to N that are co-prime with N
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++
#include <iostream>
using namespace std;
int gcd( int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
int findSum(unsigned int N)
{
unsigned int sum = 0;
for ( int i = 1; i < N; i++) {
if (gcd(i, N) == 1) {
sum += i;
}
}
return sum;
}
int main()
{
int N = 5;
cout << findSum(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int gcd( int a,
int b)
{
if (a == 0 )
return b;
return gcd(b % a, a);
}
static int findSum( int N)
{
int sum = 0 ;
for ( int i = 1 ; i < N; i++)
{
if (gcd(i, N) == 1 )
{
sum += i;
}
}
return sum;
}
public static void main(String[] args)
{
int N = 5 ;
System.out.print(findSum(N));
}
}
|
Python3
def gcd(a, b):
if (a = = 0 ):
return b;
return gcd(b % a, a);
def findSum(N):
sum = 0 ;
for i in range ( 1 , N):
if (gcd(i, N) = = 1 ):
sum + = i;
return sum ;
if __name__ = = '__main__' :
N = 5 ;
print (findSum(N));
|
C#
using System;
class GFG{
static int gcd( int a,
int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int findSum( int N)
{
int sum = 0;
for ( int i = 1; i < N; i++)
{
if (gcd(i, N) == 1)
{
sum += i;
}
}
return sum;
}
public static void Main(String[] args)
{
int N = 5;
Console.Write(findSum(N));
}
}
|
Javascript
<script>
function gcd(a, b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
function findSum(N)
{
var sum = 0;
for ( var i = 1; i < N; i++) {
if (gcd(i, N) == 1) {
sum += i;
}
}
return sum;
}
var N = 5;
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)
Last Updated :
05 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...