Count of integers up to N which are non divisors and non coprime with N
Last Updated :
02 Dec, 2021
Given an integer N, the task is to find the count of all possible integers less than N satisfying the following properties:
- The number is not coprime with N i.e their GCD is greater than 1.
- The number is not a divisor of N.
Examples:
Input: N = 10
Output: 3
Explanation:
All possible integers which are less than 10 and are neither divisors nor coprime with 10, are {4, 6, 8}.
Therefore, the required count is 3.
Input: N = 42
Output: 23
Approach:
Follow the steps below to solve the problem:
Total count = N – Euler’s totient(N) – Divisor count(N)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int count( int n)
{
int phi[n + 1] = { 0 };
int divs[n + 1] = { 0 };
for ( int i = 1; i <= n; i++) {
phi[i] += i;
for ( int j = i * 2; j <= n; j += i)
phi[j] -= phi[i];
for ( int j = i; j <= n; j += i)
divs[j]++;
}
return (n - phi[n] - divs[n] + 1);
}
int main()
{
int N = 42;
cout << count(N);
return 0;
}
|
Java
import java.util.Arrays;
class GFG{
public static int count( int n)
{
int []phi = new int [n + 1 ];
Arrays.fill(phi, 0 );
int []divs = new int [n + 1 ];
Arrays.fill(divs, 0 );
for ( int i = 1 ; i <= n; i++)
{
phi[i] += i;
for ( int j = i * 2 ; j <= n; j += i)
phi[j] -= phi[i];
for ( int j = i; j <= n; j += i)
divs[j]++;
}
return (n - phi[n] - divs[n] + 1 );
}
public static void main(String []args)
{
int N = 42 ;
System.out.println(count(N));
}
}
|
Python3
def count(n):
phi = [ 0 ] * (n + 1 )
divs = [ 0 ] * (n + 1 )
for i in range ( 1 , n + 1 ):
phi[i] + = i
for j in range (i * 2 , n + 1 , i):
phi[j] - = phi[i];
for j in range (i, n + 1 , i):
divs[j] + = 1
return (n - phi[n] - divs[n] + 1 );
if __name__ = = '__main__' :
N = 42
print (count(N))
|
C#
using System;
class GFG{
public static int count( int n)
{
int []phi = new int [n + 1];
int []divs = new int [n + 1];
for ( int i = 1; i <= n; i++)
{
phi[i] += i;
for ( int j = i * 2; j <= n; j += i)
phi[j] -= phi[i];
for ( int j = i; j <= n; j += i)
divs[j]++;
}
return (n - phi[n] - divs[n] + 1);
}
public static void Main(String []args)
{
int N = 42;
Console.WriteLine(count(N));
}
}
|
Javascript
<script>
function count(n)
{
let phi = [];
let divs = [];
for (let i = 1; i <= n; i++)
{
phi[i] = 0;
divs[i] = 0;
}
for (let i = 1; i <= n; i++)
{
phi[i] += i;
for (let j = i * 2; j <= n; j += i)
phi[j] -= phi[i];
for (let j = i; j <= n; j += i)
divs[j]++;
}
return (n - phi[n] - divs[n] + 1);
}
let N = 42;
document.write(count(N));
</script>
|
Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...