Numbers with sum of digits equal to the sum of digits of its all prime factor

Given a range, the task is to find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum.
Examples:Â
Â
Input: l = 2, r = 10 Output: 5 2, 3, 4, 5 and 7 are such numbers Input: l = 15, r = 22 Output: 3 17, 19 and 22 are such numbers As, 17 and 19 are already prime. Prime Factors of 22 = 2 * 11 i.e For 22, Sum of digits is 2+2 = 4 For 2 * 11, Sum of digits is 2 + 1 + 1 = 4
Â
Approach: An efficient solution is to modify Sieve of Eratosthenes such that for each non-prime number it stores smallest prime factor(prefactor).Â
Â
- Preprocess to find the smallest prime factor for all the numbers between 2 and MAXN. This can be done by breaking up the number into its prime factors in constant time because for each number if it is a prime, it has no prefactor.
- Otherwise, we can break it up to into a prime factor and the other part of the number which may or may not be prime.
- And repeat this process of extracting factors till it becomes a prime.
- Then check if the digits of that number is equal to the digits of prime factors by adding the digits of smallest prime factor i.e
Digits_Sum of SPF[n] + Digits_Sum of (n / SPF[n])
- Now make prefix sum array that counts how many valid numbers are there up to a number N. For each query, print:
ans[R] – ans[L-1]
Below is the implementation of above approach:Â
Â
C++
// C++ program to Find the count of the numbers// in the given range such that the sum of its// digit is equal to the sum of all its prime// factors digits sum.#include <bits/stdc++.h>using namespace std;Â
// maximum size of number#define MAXN 100005Â
// array to store smallest prime factor of numberint spf[MAXN] = { 0 };Â
// array to store sum of digits of a numberint sum_digits[MAXN] = { 0 };Â
// boolean array to check given number is countable// for required answer or not.bool isValid[MAXN] = { 0 };Â
// prefix array to store answerint ans[MAXN] = { 0 };Â
// Calculating SPF (Smallest Prime Factor) for every// number till MAXN.void Smallest_prime_factor(){    // marking smallest prime factor for every    // number to be itself.    for (int i = 1; i < MAXN; i++)        spf[i] = i;Â
    // separately marking spf for every even    // number as 2    for (int i = 4; i < MAXN; i += 2)        spf[i] = 2;Â
    for (int i = 3; i * i <= MAXN; i += 2)Â
        // checking if i is prime        if (spf[i] == i)Â
            // marking SPF for all numbers divisible by i            for (int j = i * i; j < MAXN; j += i)Â
                // marking spf[j] if it is not                // previously marked                if (spf[j] == j)                    spf[j] = i;}Â
// Function to find sum of digits in a numberint Digit_Sum(int copy){Â Â Â Â int d = 0;Â Â Â Â while (copy) {Â Â Â Â Â Â Â Â d += copy % 10;Â Â Â Â Â Â Â Â copy /= 10;Â Â Â Â }Â
    return d;}Â
// find sum of digits of all numbers up to MAXNvoid Sum_Of_All_Digits(){    for (int n = 2; n < MAXN; n++) {        // add sum of digits of least         // prime factor and n/spf[n]        sum_digits[n] = sum_digits[n / spf[n]]                            + Digit_Sum(spf[n]);Â
        // if it is valid make isValid true        if (Digit_Sum(n) == sum_digits[n])            isValid[n] = true;    }Â
    // prefix sum to compute answer    for (int n = 2; n < MAXN; n++) {        if (isValid[n])            ans[n] = 1;        ans[n] += ans[n - 1];    }}Â
// Driver codeint main(){Â Â Â Â Smallest_prime_factor();Â Â Â Â Sum_Of_All_Digits();Â
    // decleartion    int l, r;Â
    // print answer for required range    l = 2, r = 3;    cout << "Valid numbers in the range " << l << " "         << r << " are " << ans[r] - ans[l - 1] << endl;Â
    // print answer for required range    l = 2, r = 10;    cout << "Valid numbers in the range " << l << " "         << r << " are " << ans[r] - ans[l - 1] << endl;Â
  return 0;} |
Java
// Java program to Find the count // of the numbers in the given // range such that the sum of its// digit is equal to the sum of // all its prime factors digits sum.import java.io.*;Â
class GFG {Â
// maximum size of numberstatic int MAXN = 100005;Â
// array to store smallest // prime factor of numberstatic int spf[] = new int[MAXN];Â
// array to store sum // of digits of a numberstatic int sum_digits[] = new int[MAXN];Â
// boolean array to check// given number is countable// for required answer or not.static boolean isValid[] = new boolean[MAXN];Â
// prefix array to store answerstatic int ans[] = new int[MAXN];Â
// Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.static void Smallest_prime_factor(){    // marking smallest prime factor     // for every number to be itself.    for (int i = 1; i < MAXN; i++)        spf[i] = i;Â
    // separately marking spf     // for every even number as 2    for (int i = 4; i < MAXN; i += 2)        spf[i] = 2;Â
    for (int i = 3;              i * i <= MAXN; i += 2)Â
        // checking if i is prime        if (spf[i] == i)Â
            // marking SPF for all            // numbers divisible by i            for (int j = i * i;                      j < MAXN; j += i)Â
                // marking spf[j] if it                // is not previously marked                if (spf[j] == j)                    spf[j] = i;}Â
// Function to find sum // of digits in a numberstatic int Digit_Sum(int copy){Â Â Â Â int d = 0;Â Â Â Â while (copy > 0) Â Â Â Â {Â Â Â Â Â Â Â Â d += copy % 10;Â Â Â Â Â Â Â Â copy /= 10;Â Â Â Â }Â
    return d;}Â
// find sum of digits of // all numbers up to MAXNstatic void Sum_Of_All_Digits(){    for (int n = 2; n < MAXN; n++)    {        // add sum of digits of least         // prime factor and n/spf[n]        sum_digits[n] = sum_digits[n / spf[n]]                           + Digit_Sum(spf[n]);Â
        // if it is valid make isValid true        if (Digit_Sum(n) == sum_digits[n])            isValid[n] = true;    }Â
    // prefix sum to compute answer    for (int n = 2; n < MAXN; n++)     {        if (isValid[n])            ans[n] = 1;        ans[n] += ans[n - 1];    }}Â
// Driver codepublic static void main (String[] args) {    Smallest_prime_factor();    Sum_Of_All_Digits();         // declaration    int l, r;         // print answer for required range    l = 2; r = 3;    System.out.println("Valid numbers in the range " +                                l + " " + r + " are " +                               (ans[r] - ans[l - 1] ));         // print answer for required range    l = 2; r = 10;    System.out.println("Valid numbers in the range " +                                l + " " + r + " are " +                                (ans[r] - ans[l - 1]));}}Â
// This code is contributed// by Inder |
Python 3
# Python 3 program to Find the count of # the numbers in the given range such# that the sum of its digit is equal to# the sum of all its prime factors digits sum.Â
# maximum size of numberMAXN = 100005Â
# array to store smallest prime# factor of numberspf = [0] * MAXNÂ
# array to store sum of digits of a numbersum_digits = [0] * MAXNÂ
# boolean array to check given number # is countable for required answer or not.isValid = [0] * MAXNÂ
# prefix array to store answerans = [0]*MAXNÂ
# Calculating SPF (Smallest Prime Factor) # for every number till MAXN.def Smallest_prime_factor():Â
    # marking smallest prime factor    # for every number to be itself.    for i in range(1, MAXN):        spf[i] = iÂ
    # separately marking spf for     # every even number as 2    for i in range(4, MAXN, 2):        spf[i] = 2Â
    i = 3    while i * i <= MAXN: Â
        # checking if i is prime        if (spf[i] == i):Â
            # marking SPF for all numbers            # divisible by i            for j in range(i * i, MAXN, i):Â
                # marking spf[j] if it is not                # previously marked                if (spf[j] == j):                    spf[j] = i                             i += 2Â
# Function to find sum of digits # in a numberdef Digit_Sum(copy):Â Â Â Â Â Â Â Â Â d = 0Â Â Â Â while (copy) :Â Â Â Â Â Â Â Â d += copy % 10Â Â Â Â Â Â Â Â copy //= 10Â
    return dÂ
# find sum of digits of all# numbers up to MAXNdef Sum_Of_All_Digits():Â
    for n in range(2, MAXN) :                 # add sum of digits of least         # prime factor and n/spf[n]        sum_digits[n] = (sum_digits[n // spf[n]] +                         Digit_Sum(spf[n]))Â
        # if it is valid make isValid true        if (Digit_Sum(n) == sum_digits[n]):            isValid[n] = TrueÂ
    # prefix sum to compute answer    for n in range(2, MAXN) :        if (isValid[n]):            ans[n] = 1        ans[n] += ans[n - 1]Â
# Driver codeif __name__ == "__main__":Â Â Â Â Â Â Â Â Â Smallest_prime_factor()Â Â Â Â Sum_Of_All_Digits()Â
    # print answer for required range    l = 2    r = 3    print("Valid numbers in the range", l, r,                  "are", ans[r] - ans[l - 1])Â
    # print answer for required range    l = 2    r = 10    print("Valid numbers in the range", l, r,                   "are", ans[r] - ans[l - 1])Â
# This code is contributed by ita_c |
C#
// C# program to Find the count // of the numbers in the given // range such that the sum of its// digit is equal to the sum of // all its prime factors digits sum.using System;Â
class GFG {Â
// maximum size of numberstatic int MAXN = 100005;Â
// array to store smallest // prime factor of numberstatic int []spf = new int[MAXN];Â
// array to store sum // of digits of a numberstatic int []sum_digits = new int[MAXN];Â
// boolean array to check// given number is countable// for required answer or not.static bool []isValid = new bool[MAXN];Â
// prefix array to store answerstatic int []ans = new int[MAXN];Â
// Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.static void Smallest_prime_factor(){    // marking smallest prime factor     // for every number to be itself.    for (int i = 1; i < MAXN; i++)        spf[i] = i;Â
    // separately marking spf     // for every even number as 2    for (int i = 4; i < MAXN; i += 2)        spf[i] = 2;Â
    for (int i = 3;              i * i <= MAXN; i += 2)Â
        // checking if i is prime        if (spf[i] == i)Â
            // marking SPF for all            // numbers divisible by i            for (int j = i * i;                      j < MAXN; j += i)Â
                // marking spf[j] if it                // is not previously marked                if (spf[j] == j)                    spf[j] = i;}Â
// Function to find sum // of digits in a numberstatic int Digit_Sum(int copy){Â Â Â Â int d = 0;Â Â Â Â while (copy > 0) Â Â Â Â {Â Â Â Â Â Â Â Â d += copy % 10;Â Â Â Â Â Â Â Â copy /= 10;Â Â Â Â }Â
    return d;}Â
// find sum of digits of // all numbers up to MAXNstatic void Sum_Of_All_Digits(){    for (int n = 2; n < MAXN; n++)    {        // add sum of digits of least         // prime factor and n/spf[n]        sum_digits[n] = sum_digits[n / spf[n]] +                              Digit_Sum(spf[n]);Â
        // if it is valid make         // isValid true        if (Digit_Sum(n) == sum_digits[n])            isValid[n] = true;    }Â
    // prefix sum to compute answer    for (int n = 2; n < MAXN; n++)     {        if (isValid[n])            ans[n] = 1;        ans[n] += ans[n - 1];    }}Â
// Driver codepublic static void Main () {    Smallest_prime_factor();    Sum_Of_All_Digits();         // declaration    int l, r;         // print answer for required range    l = 2; r = 3;    Console.WriteLine("Valid numbers in the range " +                               l + " " + r + " are " +                              (ans[r] - ans[l - 1] ));         // print answer for required range    l = 2; r = 10;    Console.WriteLine("Valid numbers in the range " +                               l + " " + r + " are " +                               (ans[r] - ans[l - 1]));}}Â
// This code is contributed// by Subhadeep |
Javascript
<script>Â
// Javascript program to Find the count // of the numbers in the given // range such that the sum of its// digit is equal to the sum of // all its prime factors digits sum.Â
// maximum size of numbervar MAXN = 100005;Â
// array to store smallest // prime factor of numbervar spf = Array.from({length: MAXN}, (_, i) => 0);Â
// array to store sum // of digits of a numbervar sum_digits = Array.from({length: MAXN}, (_, i) => 0);Â
// boolean array to check// given number is countable// for required answer or not.var isValid = Array.from({length: MAXN}, (_, i) => false);Â
// prefix array to store answervar ans = Array.from({length: MAXN}, (_, i) => 0);Â
// Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.function Smallest_prime_factor(){    // marking smallest prime factor     // for every number to be itself.    for (i = 1; i < MAXN; i++)        spf[i] = i;Â
    // separately marking spf     // for every even number as 2    for (i = 4; i < MAXN; i += 2)        spf[i] = 2;Â
    for (i = 3;              i * i <= MAXN; i += 2)Â
        // checking if i is prime        if (spf[i] == i)Â
            // marking SPF for all            // numbers divisible by i            for (j = i * i;                      j < MAXN; j += i)Â
                // marking spf[j] if it                // is not previously marked                if (spf[j] == j)                    spf[j] = i;}Â
// Function to find sum // of digits in a numberfunction Digit_Sum(copy){Â Â Â Â var d = 0;Â Â Â Â while (copy > 0) Â Â Â Â {Â Â Â Â Â Â Â Â d += copy % 10;Â Â Â Â Â Â Â Â copy = parseInt(copy/10);Â Â Â Â }Â
    return d;}Â
// find sum of digits of // all numbers up to MAXNfunction Sum_Of_All_Digits(){    for (n = 2; n < MAXN; n++)    {        // add sum of digits of least         // prime factor and n/spf[n]        sum_digits[n] = sum_digits[parseInt(n / spf[n])]                           + Digit_Sum(spf[n]);Â
        // if it is valid make isValid true        if (Digit_Sum(n) == sum_digits[n])            isValid[n] = true;    }Â
    // prefix sum to compute answer    for (n = 2; n < MAXN; n++)     {        if (isValid[n])            ans[n] = 1;        ans[n] += ans[n - 1];    }}Â
// Driver codeSmallest_prime_factor();Sum_Of_All_Digits();Â
// declarationvar l, r;Â
// print answer for required rangel = 2; r = 3;document.write("Valid numbers in the range " + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â l + " " + r + " are " + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â (ans[r] - ans[l - 1] ));Â
// print answer for required rangel = 2; r = 10;document.write("<br>Valid numbers in the range " + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â l + " " + r + " are " + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â (ans[r] - ans[l - 1]));Â
Â
// This code contributed by shikhasingrajput Â
</script> |
Output:Â
Valid numbers in the range 2 3 are 2 Valid numbers in the range 2 10 are 5
Â
Time Complexity: O(n log n)
Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



