Count of interesting primes upto N - GeeksforGeeks

24 Nov, 2021
Given a number N, the task is to find the number of interesting primes less than equal to N.An interesting prime is any prime number which can be written as a2 + b4, where a and b are positive integers. For e.g. The smallest interesting prime number is 2 = 12 + 14. 
Examples: 
Input: N = 10 Output: 2 2 = 12 + 14 5 = 22 + 14 Both are interesting primes less than equal to 10
Input: N = 1000 Output: 28 
Naive Approach:  
Iterate through all numbers from 1 to N.For each number, check whether its prime or not.If it is prime, then check whether it can be represented as a2 + b4 by: Iterate through all possible values of b from 1 to N1/4.For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not).
Iterate through all numbers from 1 to N.
For each number, check whether its prime or not.
If it is prime, then check whether it can be represented as a2 + b4 by: Iterate through all possible values of b from 1 to N1/4.For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not).
Iterate through all possible values of b from 1 to N1/4.
For each value of b, check whether N – b4 is a perfect square or not (i.e it can be a2 or not).
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program to find the number// of interesting primes up to N #include <bits/stdc++.h>using namespace std; // Function to check if a number// is prime or notbool isPrime(int n){     int flag = 1;     // If n is divisible by any    // number between 2 and sqrt(n),    // it is not prime    for (int i = 2; i * i <= n; i++) {        if (n % i == 0) {            flag = 0;            break;        }    }     return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notbool isPerfectSquare(int x){    // Find floating point value of    // square root of x.    long double sr = sqrt(x);     // If square root is an integer    return ((sr - floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.int countInterestingPrimes(int n){     int answer = 0;    for (int i = 2; i <= n; i++) {         // Check whether the number        // is prime or not        if (isPrime(i)) {             // Iterate for values of b            for (int j = 1;                 j * j * j * j <= i;                 j++) {                 // Check condition for a                if (                    isPerfectSquare(                        i - j * j * j * j)) {                    answer++;                    break;                }            }        }    }     // Return the required answer    return answer;} // Driver codeint main(){    int N = 10;     cout << countInterestingPrimes(N);     return 0;}
// Java program to find the number// of interesting primes up to Nclass GFG{  // Function to check if a number// is prime or notstatic boolean isPrime(int n){      int flag = 1;      // If n is divisible by any    // number between 2 and Math.sqrt(n),    // it is not prime    for (int i = 2; i * i <= n; i++) {        if (n % i == 0) {            flag = 0;            break;        }    }      return (flag == 1 ? true : false);}  // Function to check if a number// is perfect square or notstatic boolean isPerfectSquare(int x){    // Find floating point value of    // square root of x.    double sr = Math.sqrt(x);      // If square root is an integer    return ((sr - Math.floor(sr)) == 0);}  // Function to find the number of interesting// primes less than equal to N.static int countInterestingPrimes(int n){      int answer = 0;    for (int i = 2; i <= n; i++) {          // Check whether the number        // is prime or not        if (isPrime(i)) {              // Iterate for values of b            for (int j = 1;                 j * j * j * j <= i;                 j++) {                  // Check condition for a                if (                    isPerfectSquare(                        i - j * j * j * j)) {                    answer++;                    break;                }            }        }    }      // Return the required answer    return answer;}  // Driver codepublic static void main(String[] args){    int N = 10;      System.out.print(countInterestingPrimes(N));}} // This code is contributed by Princi Singh
# Python3 program to find the number# of interesting primes up to Nimport math # Function to check if a number# is prime or notdef isPrime(n):     flag = 1     # If n is divisible by any    # number between 2 and sqrt(n),    # it is not prime    i = 2    while(i * i <= n):        if (n % i == 0):            flag = 0            break        i += 1         return (True if flag == 1 else False) # Function to check if a number# is perfect square or notdef isPerfectSquare(x):     # Find floating povalue of    # square root of x.    sr = math.sqrt(x)     # If square root is an integer    return ((sr - math.floor(sr)) == 0) # Function to find the number of interesting# primes less than equal to N.def countInterestingPrimes(n):     answer = 0    for i in range(2, n):         # Check whether the number        # is prime or not        if (isPrime(i)):             # Iterate for values of b            j = 1            while(j * j * j * j <= i):                 # Check condition for a                if (isPerfectSquare(i - j * j *                                        j * j)):                    answer += 1                    break                j += 1     # Return the required answer    return answer # Driver codeif __name__=='__main__':     N = 10     print(countInterestingPrimes(N)) # This code is contributed by AbhiThakur
// C# program to find the number// of interesting primes up to Nusing System;using System.Collections.Generic; class GFG{   // Function to check if a number// is prime or notstatic bool isPrime(int n){       int flag = 1;       // If n is divisible by any    // number between 2 and Math.Sqrt(n),    // it is not prime    for (int i = 2; i * i <= n; i++) {        if (n % i == 0) {            flag = 0;            break;        }    }       return (flag == 1 ? true : false);}   // Function to check if a number// is perfect square or notstatic bool isPerfectSquare(int x){    // Find floating point value of    // square root of x.    double sr = Math.Sqrt(x);       // If square root is an integer    return ((sr - Math.Floor(sr)) == 0);}   // Function to find the number of interesting// primes less than equal to N.static int countInterestingPrimes(int n){       int answer = 0;    for (int i = 2; i <= n; i++) {           // Check whether the number        // is prime or not        if (isPrime(i)) {               // Iterate for values of b            for (int j = 1;                 j * j * j * j <= i;                 j++) {                   // Check condition for a                if (                    isPerfectSquare(                        i - j * j * j * j)) {                    answer++;                    break;                }            }        }    }       // Return the required answer    return answer;}   // Driver codepublic static void Main(String[] args){    int N = 10;       Console.Write(countInterestingPrimes(N));}} // This code is contributed by Rajput-Ji
<script>// Java  script program to find the number// of interesting primes up to N // Function to check if a number// is prime or notfunction isPrime( n){     let flag = 1;     // If n is divisible by any    // number between 2 and Math.sqrt(n),    // it is not prime    for (let i = 2; i * i <= n; i++) {        if (n % i == 0) {            flag = 0;            break;        }    }     return (flag == 1 ? true : false);} // Function to check if a number// is perfect square or notfunction isPerfectSquare( x){    // Find floating point value of    // square root of x.    let sr = Math.sqrt(x);     // If square root is an integer    return ((sr - Math.floor(sr)) == 0);} // Function to find the number of interesting// primes less than equal to N.function countInterestingPrimes( n){     let answer = 0;    for (let i = 2; i <= n; i++) {         // Check whether the number        // is prime or not        if (isPrime(i)) {             // Iterate for values of b            for (let j = 1;                j * j * j * j <= i;                j++) {                 // Check condition for a                if (                    isPerfectSquare(                        i - j * j * j * j)) {                    answer++;                    break;                }            }        }    }     // Return the required answer    return answer;} // Driver code     let N = 10;     document.write(countInterestingPrimes(N));   // This code is contributed by Bobby</script>
2
 
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: 
If we store all perfect squares and perfect quadruples up to N, then we can iterate through all the pairs and check whether the result is prime or not.To further optimise we can store all primes till N using sieve of eratosthenes and do the primality check in O(1).
If we store all perfect squares and perfect quadruples up to N, then we can iterate through all the pairs and check whether the result is prime or not.
To further optimise we can store all primes till N using sieve of eratosthenes and do the primality check in O(1).
Below is the implementation of the above approach:  
C++
Java
Python3
C#
// C++ program to find the number// of interesting primes up to N. #include <bits/stdc++.h>using namespace std; // Function to find all prime numbersvoid SieveOfEratosthenes(    int n,    unordered_set<int>& allPrimes){    // Create a boolean array "prime[0..n]"    // and initialize all entries as true.    // A value in prime[i] will finally    // be false if i is Not a prime.    bool prime[n + 1];    memset(prime, true, sizeof(prime));     for (int p = 2; p * p <= n; p++) {         // If prime[p] is not changed,        // then it is a prime        if (prime[p] == true) {             // Update all multiples of p            // greater than or equal to            // the square of it            for (int i = p * p; i <= n; i += p)                prime[i] = false;        }    }     // Store all prime numbers    for (int p = 2; p <= n; p++)        if (prime[p])            allPrimes.insert(p);} // Function to check if a number// is perfect square or notint countInterestingPrimes(int n){    // To store all primes    unordered_set<int> allPrimes;     SieveOfEratosthenes(n, allPrimes);     // To store all interseting primes    unordered_set<int> intersetingPrimes;     vector<int> squares, quadruples;     // Store all perfect squares    for (int i = 1; i * i <= n; i++) {        squares.push_back(i * i);    }     // Store all perfect quadruples    for (int i = 1; i * i * i * i <= n; i++) {        quadruples.push_back(i * i * i * i);    }     // Store all interseting primes    for (auto a : squares) {        for (auto b : quadruples) {            if (allPrimes.count(a + b))                intersetingPrimes.insert(a + b);        }    }     // Return count of interseting primes    return intersetingPrimes.size();} // Driver codeint main(){    int N = 10;     cout << countInterestingPrimes(N);     return 0;}
// Java program to find the number// of interesting primes up to N.import java.util.*; class GFG{  // Function to find all prime numbersstatic void SieveOfEratosthenes(    int n, HashSet<Integer> allPrimes){    // Create a boolean array "prime[0..n]"    // and initialize all entries as true.    // A value in prime[i] will finally    // be false if i is Not a prime.    boolean []prime = new boolean[n + 1];    Arrays.fill(prime, true);      for (int p = 2; p * p <= n; p++) {          // If prime[p] is not changed,        // then it is a prime        if (prime[p] == true) {              // Update all multiples of p            // greater than or equal to            // the square of it            for (int i = p * p; i <= n; i += p)                prime[i] = false;        }    }      // Store all prime numbers    for (int p = 2; p <= n; p++)        if (prime[p])            allPrimes.add(p);}  // Function to check if a number// is perfect square or notstatic int countInterestingPrimes(int n){    // To store all primes    HashSet<Integer> allPrimes = new HashSet<Integer>();      SieveOfEratosthenes(n, allPrimes);      // To store all interseting primes    HashSet<Integer> intersetingPrimes = new HashSet<Integer>();      Vector<Integer> squares = new Vector<Integer>()            , quadruples = new Vector<Integer>();      // Store all perfect squares    for (int i = 1; i * i <= n; i++) {        squares.add(i * i);    }      // Store all perfect quadruples    for (int i = 1; i * i * i * i <= n; i++) {        quadruples.add(i * i * i * i);    }      // Store all interseting primes    for (int a : squares) {        for (int b : quadruples) {            if (allPrimes.contains(a + b))                intersetingPrimes.add(a + b);        }    }      // Return count of interseting primes    return intersetingPrimes.size();}  // Driver codepublic static void main(String[] args){    int N = 10;      System.out.print(countInterestingPrimes(N));}} // This code is contributed by 29AjayKumar
# Python3 program to find the number# of interesting primes up to N. # Function to find all prime numbersdef SieveOfEratosthenes(n, allPrimes):         # Create a boolean array "prime[0..n]"    # and initialize all entries as true.    # A value in prime[i] will finally    # be false if i is Not a prime.    prime = [True] * (n + 1)         p = 2    while p * p <= n:                 # If prime[p] is not changed,        # then it is a prime        if prime[p] == True:                         # Update all multiples of p            # greater than or equal to            # the square of it            for i in range(p * p, n + 1, p):                prime[i] = False        p += 1         # Store all prime numbers    for p in range(2, n + 1):        if prime[p]:            allPrimes.add(p) # Function to check if a number# is perfect square or notdef countInterestingPrimes(n):         # To store all primes    allPrimes = set()         # To store all interseting primes    SieveOfEratosthenes(n, allPrimes)         # To store all interseting primes    interestingPrimes = set()         squares, quadruples = [], []         # Store all perfect squares    i = 1    while i * i <= n:        squares.append(i * i)        i += 1         # Store all perfect quadruples    i = 1    while i * i * i * i <= n:        quadruples.append(i * i * i * i)        i += 1         # Store all interseting primes    for a in squares:        for b in quadruples:            if a + b in allPrimes:                interestingPrimes.add(a + b)                     # Return count of interseting primes    return len(interestingPrimes) # Driver codeN = 10print(countInterestingPrimes(N)) # This code is contributed by Shivam Singh
// C# program to find the number// of interesting primes up to N.using System;using System.Collections.Generic; class GFG{   // Function to find all prime numbersstatic void SieveOfEratosthenes(    int n, HashSet<int> allPrimes){    // Create a bool array "prime[0..n]"    // and initialize all entries as true.    // A value in prime[i] will finally    // be false if i is Not a prime.    bool []prime = new bool[n + 1];    for(int i = 0; i < n + 1; i++)        prime[i] =  true;       for (int p = 2; p * p <= n; p++) {           // If prime[p] is not changed,        // then it is a prime        if (prime[p] == true) {               // Update all multiples of p            // greater than or equal to            // the square of it            for (int i = p * p; i <= n; i += p)                prime[i] = false;        }    }       // Store all prime numbers    for (int p = 2; p <= n; p++)        if (prime[p])            allPrimes.Add(p);}   // Function to check if a number// is perfect square or notstatic int countInterestingPrimes(int n){    // To store all primes    HashSet<int> allPrimes = new HashSet<int>();       SieveOfEratosthenes(n, allPrimes);       // To store all interseting primes    HashSet<int> intersetingPrimes = new HashSet<int>();       List<int> squares = new List<int>()            , quadruples = new List<int>();       // Store all perfect squares    for (int i = 1; i * i <= n; i++) {        squares.Add(i * i);    }       // Store all perfect quadruples    for (int i = 1; i * i * i * i <= n; i++) {        quadruples.Add(i * i * i * i);    }       // Store all interseting primes    foreach (int a in squares) {        foreach (int b in quadruples) {            if (allPrimes.Contains(a + b))                intersetingPrimes.Add(a + b);        }    }       // Return count of interseting primes    return intersetingPrimes.Count;}   // Driver codepublic static void Main(String[] args){    int N = 10;       Console.Write(countInterestingPrimes(N));}}  // This code is contributed by Rajput-Ji
2
 
Time Complexity: O(N)
Auxiliary Space: O(N)
princi singh
Rajput-Ji
abhaysingh290895
29AjayKumar
SHIVAMSINGH67
gottumukkalabobby
sagar0719kumar
subham348
math
maths-perfect-square
Algorithms
Greedy
Mathematical
Greedy
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
K means Clustering - Introduction
Program for SSTF disk scheduling algorithm
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Huffman Coding | Greedy Algo-3