Find all numbers between range L to R such that sum of digit and sum of square of digit is prime

Given the range L and R, count all numbers between L to R such that sum of digits of each number and sum of square of digits of each number is Prime.
Note: 10 <= [L, R] <= 108
Examples:Â Â
Input: L = 10, R = 20Â
Output: 4Â
Such types of numbers are: 11 12 14 16Input: L = 100, R = 130Â
Output: 9
Such types of numbers are : 101 102 104 106 110 111 113 119 120Â Â
Naive Approach:Â
Just get the sum of the digits of each number and the sum of the square of digits of each number and check whether they are both prime or not.
Â
Efficient Approach:Â Â
- Now, if you look closely into the range, the number is 108 ie., and the largest number less than this will be 99999999, and the maximum number, can be formed is 8 * ( 9 * 9 ) = 648 (as the sum of squares of digits is 92 + 92 + … 8times,) so, we need only primes up to 648 only which can be done using Sieve of Eratosthenes.
- Now iterate for each number in the range and check whether it satisfies the above conditions or not.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Sieve of prime numbersvoid primesieve(vector<bool>& prime){    // Sieve to store whether a    // number is prime or not in    // O(nlog(log(n)))    prime[1] = false;Â
    for (int p = 2; p * p <= 650; p++) {        if (prime[p] == true) {            for (int i = p * 2; i <= 650; i += p)                prime[i] = false;        }    }}Â
// Function to return sum of digit// and sum of square of digitpair<int, int> sum_sqsum(int n){Â
    int sum = 0;    int sqsum = 0;    int x;Â
    // Until number is not    // zero    while (n) {        x = n % 10;        sum += x;        sqsum += x * x;        n /= 10;    }Â
    return (make_pair(sum, sqsum));}Â
// Function to return the count// of number form L to R// whose sum of digits and// sum of square of digits// are primeint countnumber(int L, int R){Â
    vector<bool> prime(651, true);Â
    primesieve(prime);Â
    int cnt = 0;Â
    // Iterate for each value    // in the range of L to R    for (int i = L; i <= R; i++) {Â
        // digit.first stores sum of digits        // digit.second stores sum of        // square of digit        pair<int, int> digit = sum_sqsum(i);Â
        // If sum of digits and sum of        // square of digit both are        // prime then increment the count        if (prime[digit.first]            && prime[digit.second]) {            cnt += 1;        }    }Â
    return cnt;}Â
// Driver Codeint main(){Â
    int L = 10;    int R = 20;Â
    cout << countnumber(L, R);} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG {static class pair{ Â Â Â Â int first, second; Â Â Â Â public pair(int first, int second) Â Â Â Â { Â Â Â Â Â Â Â Â this.first = first; Â Â Â Â Â Â Â Â this.second = second; Â Â Â Â } }Â
// Sieve of prime numbersstatic void primesieve(boolean []prime){    // Sieve to store whether a    // number is prime or not in    // O(nlog(log(n)))    prime[1] = false;Â
    for (int p = 2; p * p <= 650; p++)    {        if (prime[p] == true)        {            for (int i = p * 2; i <= 650; i += p)                prime[i] = false;        }    }}Â
// Function to return sum of digit// and sum of square of digitstatic pair sum_sqsum(int n){Â Â Â Â int sum = 0;Â Â Â Â int sqsum = 0;Â Â Â Â int x;Â
    // Until number is not    // zero    while (n > 0)    {        x = n % 10;        sum += x;        sqsum += x * x;        n /= 10;    }    return (new pair(sum, sqsum));}Â
// Function to return the count// of number form L to R// whose sum of digits and// sum of square of digits// are primestatic int countnumber(int L, int R){Â Â Â Â boolean []prime = new boolean[651];Â
    Arrays.fill(prime, true);    primesieve(prime);Â
    int cnt = 0;Â
    // Iterate for each value    // in the range of L to R    for (int i = L; i <= R; i++)     {Â
        // digit.first stores sum of digits        // digit.second stores sum of        // square of digit        pair digit = sum_sqsum(i);Â
        // If sum of digits and sum of        // square of digit both are        // prime then increment the count        if (prime[digit.first] &&             prime[digit.second])         {            cnt += 1;        }    }    return cnt;}Â
// Driver Codepublic static void main(String[] args) {Â Â Â Â int L = 10;Â Â Â Â int R = 20;Â
    System.out.println(countnumber(L, R));}} Â
// This code is contributed by PrinciRaj1992 |
Python3
# Python3 implementation of the approach from math import sqrtÂ
# Sieve of prime numbers def primesieve(prime) :Â
    # Sieve to store whether a     # number is prime or not in     # O(nlog(log(n)))     prime[1] = False; Â
    for p in range(2, int(sqrt(650)) + 1) :        if (prime[p] == True) :            for i in range(p * 2, 651, p) :                 prime[i] = False; Â
# Function to return sum of digit # and sum of square of digit def sum_sqsum(n) :Â
    sum = 0;     sqsum = 0; Â
    # Until number is not     # zero     while (n) :        x = n % 10;         sum += x;         sqsum += x * x;         n //= 10; Â
    return (sum, sqsum); Â
# Function to return the count # of number form L to R # whose sum of digits and # sum of square of digits # are prime def countnumber(L, R): Â
    prime = [True] * 651; Â
    primesieve(prime); Â
    cnt = 0; Â
    # Iterate for each value     # in the range of L to R     for i in range(L, R + 1) :                 # digit.first stores sum of digits         # digit.second stores sum of         # square of digit         digit = sum_sqsum(i); Â
        # If sum of digits and sum of         # square of digit both are         # prime then increment the count         if (prime[digit[0]] and prime[digit[1]]) :            cnt += 1; Â
    return cnt; Â
# Driver Code if __name__ == "__main__" : Â
    L = 10;     R = 20; Â
    print(countnumber(L, R)); Â
# This code is contributed by AnkitRai01 |
C#
// C# implementation of the approachusing System;Â Â Â Â Â class GFG {public class pair{ Â Â Â Â public int first, second; Â Â Â Â public pair(int first, int second) Â Â Â Â { Â Â Â Â Â Â Â Â this.first = first; Â Â Â Â Â Â Â Â this.second = second; Â Â Â Â } }Â
// Sieve of prime numbersstatic void primesieve(bool []prime){    // Sieve to store whether a    // number is prime or not in    // O(nlog(log(n)))    prime[1] = false;Â
    for (int p = 2; p * p <= 650; p++)    {        if (prime[p] == true)        {            for (int i = p * 2;                     i <= 650; i += p)                prime[i] = false;        }    }}Â
// Function to return sum of digit// and sum of square of digitstatic pair sum_sqsum(int n){Â Â Â Â int sum = 0;Â Â Â Â int sqsum = 0;Â Â Â Â int x;Â
    // Until number is not    // zero    while (n > 0)    {        x = n % 10;        sum += x;        sqsum += x * x;        n /= 10;    }    return (new pair(sum, sqsum));}Â
// Function to return the count// of number form L to R// whose sum of digits and// sum of square of digits// are primestatic int countnumber(int L, int R){Â Â Â Â bool []prime = new bool[651];Â Â Â Â for (int i = 0; i < 651; i++) Â Â Â Â Â Â Â Â prime[i] = true;Â Â Â Â primesieve(prime);Â
    int cnt = 0;Â
    // Iterate for each value    // in the range of L to R    for (int i = L; i <= R; i++)     {Â
        // digit.first stores sum of digits        // digit.second stores sum of        // square of digit        pair digit = sum_sqsum(i);Â
        // If sum of digits and sum of        // square of digit both are        // prime then increment the count        if (prime[digit.first] &&             prime[digit.second])         {            cnt += 1;        }    }    return cnt;}Â
// Driver Codepublic static void Main(String[] args) {Â Â Â Â int L = 10;Â Â Â Â int R = 20;Â
    Console.WriteLine(countnumber(L, R));}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>// Javascript implementation of the approachÂ
// Sieve of prime numbersfunction primesieve(prime) {Â
    // Sieve to store whether a    // number is prime or not in    // O(nlog(log(n)))    prime[1] = false;Â
    for (let p = 2; p < Math.floor(Math.sqrt(650)) + 1; p++) {        if (prime[p] == true) {            for (let i = p * 2; i < 651; i += p) {                prime[i] = false;            }        }    }}   // Function to return sum of digit// and sum of square of digitfunction sum_sqsum(n) {Â
    let sum = 0;    let sqsum = 0;    let x;    // Until number is not    // zero    while (n) {        x = n % 10;        sum += x;        sqsum += x * x;        n = Math.floor(n / 10);    }    return [sum, sqsum];}// Function to return the count// of number form L to R// whose sum of digits and// sum of square of digits// are primefunction countnumber(L, R) {Â
    let prime = new Array(651).fill(true);Â
    primesieve(prime);Â
    let cnt = 0;Â
    // Iterate for each value    // in the range of L to R    for (let i = L; i <= R; i++) {Â
        // digit.first stores sum of digits        // digit.second stores sum of        // square of digit        let digit = sum_sqsum(i);Â
        // If sum of digits and sum of        // square of digit both are        // prime then increment the count        if (prime[digit[0]] && prime[digit[1]]) {            cnt += 1;        }    }    return cnt;}Â
// Driver CodeÂ
Â
let L = 10;let R = 20;Â
document.write(countnumber(L, R));Â
// This code is contributed by _saurabh_jaiswalÂ
</script> |
Output:Â
4
Â
Note:Â Â
- Store all numbers which satisfy the above conditions in another array and use binary search to find out how many elements in the array such that it is less than R , say cnt1 , and how many elements in the array such that it less than L , say cnt2 . Return cnt1 – cnt2Â
Time Complexity: O(log(N)) per query. - We can use a prefix array or DP approach such that it already stores how many no. are good of the above type, from index 0 to i, and return the total count by giving DP[R] – DP[L-1]Â
Time Complexity: O(1) per query.
Space Complexity: O(n).
We have used an array of size O(n) to store whether a number is prime or not.
Â
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!



