Count of numbers below N whose sum of prime divisors is K
Given two integers K and N, the task is to find the count of integers from the range [2, N – 1] whose sum of prime divisors is K
Example:
Input: N = 20, K = 7
Output: 2
7 and 10 are the only valid numbers.
sumPFactors(7) = 7
sumPFactors(10) = 2 + 5 = 7
Input: N = 25, K = 5
Output: 5
Approach: Create an array sumPF[] where sumPF[i] stores the sum of prime divisors of i which can be easily calculated using the approach used in this article. Now, initialise a variable count = 0 and run a loop from 2 to N – 1 and for every element i if sumPF[i] = K then increment the count.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
#define MAX 1000001
int countNum( int N, int K)
{
int sumPF[MAX] = { 0 };
for ( int i = 2; i < N; i++) {
if (sumPF[i] == 0) {
for ( int j = i; j < N; j += i) {
sumPF[j] += i;
}
}
}
int count = 0;
for ( int i = 2; i < N; i++) {
if (sumPF[i] == K)
count++;
}
return count;
}
int main()
{
int N = 20, K = 7;
cout << countNum(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int MAX = 1000001 ;
static int countNum( int N, int K)
{
int []sumPF = new int [MAX];
for ( int i = 2 ; i < N; i++)
{
if (sumPF[i] == 0 )
{
for ( int j = i; j < N; j += i)
{
sumPF[j] += i;
}
}
}
int count = 0 ;
for ( int i = 2 ; i < N; i++)
{
if (sumPF[i] == K)
count++;
}
return count;
}
public static void main(String[] args)
{
int N = 20 , K = 7 ;
System.out.println(countNum(N, K));
}
}
|
Python3
MAX = 1000001
def countNum(N, K) :
sumPF = [ 0 ] * MAX ;
for i in range ( 2 , N) :
if (sumPF[i] = = 0 ) :
for j in range (i, N, i) :
sumPF[j] + = i;
count = 0 ;
for i in range ( 2 , N) :
if (sumPF[i] = = K) :
count + = 1 ;
return count;
if __name__ = = "__main__" :
N = 20 ; K = 7 ;
print (countNum(N, K));
|
C#
using System;
class GFG
{
static int MAX = 1000001;
static int countNum( int N, int K)
{
int []sumPF = new int [MAX];
for ( int i = 2; i < N; i++)
{
if (sumPF[i] == 0)
{
for ( int j = i; j < N; j += i)
{
sumPF[j] += i;
}
}
}
int count = 0;
for ( int i = 2; i < N; i++)
{
if (sumPF[i] == K)
count++;
}
return count;
}
public static void Main(String[] args)
{
int N = 20, K = 7;
Console.WriteLine(countNum(N, K));
}
}
|
Javascript
<script>
const MAX = 1000001;
function countNum(N, K)
{
let sumPF = new Array(MAX).fill(0);
for (let i = 2; i < N; i++) {
if (sumPF[i] == 0) {
for (let j = i; j < N; j += i) {
sumPF[j] += i;
}
}
}
let count = 0;
for (let i = 2; i < N; i++) {
if (sumPF[i] == K)
count++;
}
return count;
}
let N = 20, K = 7;
document.write(countNum(N, K));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(MAX)
Last Updated :
18 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...