📌  相关文章
📜  检查数字是否可以表示为素数和完美平方的总和

📅  最后修改于: 2021-04-17 15:50:59             🧑  作者: Mango

给定正整数N ,任务是检查N是否可以表示为素数和完美平方的总和。如果可以用所需的形式表示N ,则打印“是” 。否则,打印“否”

例子:

天真的方法:解决给定问题的最简单方法是将所有小于或等于N的理想平方存储在数组中。对于数组中的每个理想平方,说X ,检查(N – X)是否为质数。如果发现是真的,则打印“是” 。否则,打印“否”

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if a
// number is prime or not
bool isPrime(int n)
{
    // Base Cases
    if (n <= 1)
        return false;
 
    if (n <= 3)
        return true;
 
    // Check if n is divisible by 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Iterate over every 6 number
    // from the range [5, sqrt(N)]
    for (int i = 5; i * i <= n;
         i = i + 6) {
 
        // If n is found to be non-prime
        if (n % i == 0
            || n % (i + 2) == 0) {
            return false;
        }
    }
 
    // Otherwise, return true
    return true;
}
 
// Function to check if a number can
// be represented as the sum of a prime
// number and a perfect square or not
void sumOfPrimeSquare(int n)
{
    int i = 0;
 
    // Stores all perfect
    // squares less than N
    vector squares;
    while (i * i < n) {
 
        // Store the perfect square
        // in the array
        squares.push_back(i * i);
        i++;
    }
 
    bool flag = false;
 
    // Iterate over all perfect squares
    for (i = 0; i < squares.size(); i++) {
 
        // Store the difference of
        // perfect square from n
        int difference = n - squares[i];
 
        // If difference is prime
        if (isPrime(difference)) {
 
            // Update flag
            flag = true;
 
            // Break out of the loop
            break;
        }
    }
 
    // If N is the sum of a prime
    // number and a perfect square
    if (flag) {
        cout << "Yes";
    }
    else
        cout << "No";
}
 
// Driver Code
int main()
{
    int N = 27;
    sumOfPrimeSquare(N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if a
// number is prime or not
static boolean isPrime(int n)
{
     
    // Base Cases
    if (n <= 1)
        return false;
 
    if (n <= 3)
        return true;
 
    // Check if n is divisible by 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Iterate over every 6 number
    // from the range [5, sqrt(N)]
    for(int i = 5; i * i <= n;
            i = i + 6)
    {
         
        // If n is found to be non-prime
        if (n % i == 0 || n % (i + 2) == 0)
        {
            return false;
        }
    }
 
    // Otherwise, return true
    return true;
}
 
// Function to check if a number can
// be represented as the sum of a prime
// number and a perfect square or not
static void sumOfPrimeSquare(int n)
{
    int i = 0;
 
    // Stores all perfect
    // squares less than N
    ArrayList squares = new ArrayList();
     
    while (i * i < n)
    {
         
        // Store the perfect square
        // in the array
        squares.add(i * i);
        i++;
    }
 
    boolean flag = false;
 
    // Iterate over all perfect squares
    for(i = 0; i < squares.size(); i++)
    {
         
        // Store the difference of
        // perfect square from n
        int difference = n - squares.get(i);
 
        // If difference is prime
        if (isPrime(difference))
        {
             
            // Update flag
            flag = true;
 
            // Break out of the loop
            break;
        }
    }
 
    // If N is the sum of a prime
    // number and a perfect square
    if (flag)
    {
        System.out.print("Yes");
    }
    else
        System.out.print("No");
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 27;
     
    sumOfPrimeSquare(N);
}
}
 
// This code is contributed by sanjoy_62


Python3
# Python3 program for the above approach
from math import sqrt
 
# Function to check if a
# number is prime or not
def isPrime(n):
     
    # Base Cases
    if (n <= 1):
        return False
 
    if (n <= 3):
        return True
 
    # Check if n is divisible by 2 or 3
    if (n % 2 == 0 or n % 3 == 0):
        return False
 
    # Iterate over every 6 number
    # from the range [5, sqrt(N)]
    for i in range(5, int(sqrt(n)) + 1, 6):
         
        # If n is found to be non-prime
        if (n % i == 0 or n % (i + 2) == 0):
            return False
 
    # Otherwise, return true
    return True
 
# Function to check if a number can
# be represented as the sum of a prime
# number and a perfect square or not
def sumOfPrimeSquare(n):
     
    i = 0
 
    # Stores all perfect
    # squares less than N
    squares = []
     
    while (i * i < n):
         
        # Store the perfect square
        # in the array
        squares.append(i * i)
        i += 1
 
    flag = False
 
    # Iterate over all perfect squares
    for i in range(len(squares)):
         
        # Store the difference of
        # perfect square from n
        difference = n - squares[i]
 
        # If difference is prime
        if (isPrime(difference)):
             
            # Update flag
            flag = True
 
            # Break out of the loop
            break
 
    # If N is the sum of a prime
    # number and a perfect square
    if (flag):
        print("Yes")
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
     
    N = 27
     
    sumOfPrimeSquare(N)
 
# This code is contributed by SURENDRA_GANGWAR


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to store all prime
// numbers less than or equal to N
void SieveOfEratosthenes(bool prime[],
                         int n)
{
    // Update prime[0] and
    // prime[1] as false
    prime[0] = false;
    prime[1] = false;
 
    // Iterate over the range [2, sqrt(N)]
    for (int p = 2; p * p <= n; p++) {
 
        // If p is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            // which are <= n as non-prime
            for (int i = p * p; i <= n;
                 i += p) {
 
                prime[i] = false;
            }
        }
    }
}
 
// Function to check whether a number
// can be represented as the sum of a
// prime number and a perfect square
void sumOfPrimeSquare(int n)
{
    bool flag = false;
 
    // Stores all the prime numbers
    // less than or equal to n
    bool prime[n + 1];
    memset(prime, true, sizeof(prime));
 
    // Update the array prime[]
    SieveOfEratosthenes(prime, n);
 
    // Iterate over the range [0, n]
    for (int i = 0; i <= n; i++) {
 
        // If current number
        // is non-prime
        if (!prime[i])
            continue;
 
        // Update difference
        int dif = n - i;
 
        // If difference is a
        // perfect square
        if (ceil((double)sqrt(dif))
            == floor((double)sqrt(dif))) {
 
            // If true, update flag
            // and break out of loop
            flag = true;
            break;
        }
    }
 
    // If N can be expressed as sum
    // of prime number and perfect square
    if (flag) {
        cout << "Yes";
    }
    else
        cout << "No";
}
 
// Driver Code
int main()
{
    int N = 27;
    sumOfPrimeSquare(N);
 
    return 0;
}


Python3
# Python3 program for the above approach
import math
 
# Function to store all prime
# numbers less than or equal to N
def SieveOfEratosthenes(prime, n):
     
    # Update prime[0] and
    # prime[1] as false
    prime[0] = False
    prime[1] = False
 
    # Iterate over the range [2, sqrt(N)]
    for p in range(2, int(n ** (1 / 2))):
         
        # If p is a prime
        if (prime[p] == True):
 
            # Update all multiples of p
            # which are <= n as non-prime
            for i in range(p ** 2, n + 1, p):
                prime[i] = False
 
# Function to check whether a number
# can be represented as the sum of a
# prime number and a perfect square
def sumOfPrimeSquare(n):
     
    flag = False
 
    # Stores all the prime numbers
    # less than or equal to n
    prime = [True] * (n + 1)
 
    # Update the array prime[]
    SieveOfEratosthenes(prime, n)
 
    # Iterate over the range [0, n]
    for i in range(n + 1):
 
        # If current number
        # is non-prime
        if (not prime[i]):
            continue
 
        # Update difference
        dif = n - i
 
        # If difference is a
        # perfect square
        if (math.ceil(dif ** (1 / 2)) ==
           math.floor(dif ** (1 / 2))):
 
            # If true, update flag
            # and break out of loop
            flag = True
            break
 
    # If N can be expressed as sum
    # of prime number and perfect square
    if (flag):
        print("Yes")
    else:
        print("No")
 
# Driver Code
if __name__ == "__main__":
 
    N = 27
     
    sumOfPrimeSquare(N)
     
# This code is contributed by AnkThon


输出:
Yes

时间复杂度: O(N)
辅助空间: O(√N)

高效方法:可以通过使用Eratosthenes的Sieve将所有小于N的素数存储在数组中来优化上述方法。如果存在任何质数,例如X ,则检查(N – X)是否为理想的平方。如果发现是真的,则打印“是” 。否则,打印“否”

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to store all prime
// numbers less than or equal to N
void SieveOfEratosthenes(bool prime[],
                         int n)
{
    // Update prime[0] and
    // prime[1] as false
    prime[0] = false;
    prime[1] = false;
 
    // Iterate over the range [2, sqrt(N)]
    for (int p = 2; p * p <= n; p++) {
 
        // If p is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            // which are <= n as non-prime
            for (int i = p * p; i <= n;
                 i += p) {
 
                prime[i] = false;
            }
        }
    }
}
 
// Function to check whether a number
// can be represented as the sum of a
// prime number and a perfect square
void sumOfPrimeSquare(int n)
{
    bool flag = false;
 
    // Stores all the prime numbers
    // less than or equal to n
    bool prime[n + 1];
    memset(prime, true, sizeof(prime));
 
    // Update the array prime[]
    SieveOfEratosthenes(prime, n);
 
    // Iterate over the range [0, n]
    for (int i = 0; i <= n; i++) {
 
        // If current number
        // is non-prime
        if (!prime[i])
            continue;
 
        // Update difference
        int dif = n - i;
 
        // If difference is a
        // perfect square
        if (ceil((double)sqrt(dif))
            == floor((double)sqrt(dif))) {
 
            // If true, update flag
            // and break out of loop
            flag = true;
            break;
        }
    }
 
    // If N can be expressed as sum
    // of prime number and perfect square
    if (flag) {
        cout << "Yes";
    }
    else
        cout << "No";
}
 
// Driver Code
int main()
{
    int N = 27;
    sumOfPrimeSquare(N);
 
    return 0;
}

Python3

# Python3 program for the above approach
import math
 
# Function to store all prime
# numbers less than or equal to N
def SieveOfEratosthenes(prime, n):
     
    # Update prime[0] and
    # prime[1] as false
    prime[0] = False
    prime[1] = False
 
    # Iterate over the range [2, sqrt(N)]
    for p in range(2, int(n ** (1 / 2))):
         
        # If p is a prime
        if (prime[p] == True):
 
            # Update all multiples of p
            # which are <= n as non-prime
            for i in range(p ** 2, n + 1, p):
                prime[i] = False
 
# Function to check whether a number
# can be represented as the sum of a
# prime number and a perfect square
def sumOfPrimeSquare(n):
     
    flag = False
 
    # Stores all the prime numbers
    # less than or equal to n
    prime = [True] * (n + 1)
 
    # Update the array prime[]
    SieveOfEratosthenes(prime, n)
 
    # Iterate over the range [0, n]
    for i in range(n + 1):
 
        # If current number
        # is non-prime
        if (not prime[i]):
            continue
 
        # Update difference
        dif = n - i
 
        # If difference is a
        # perfect square
        if (math.ceil(dif ** (1 / 2)) ==
           math.floor(dif ** (1 / 2))):
 
            # If true, update flag
            # and break out of loop
            flag = True
            break
 
    # If N can be expressed as sum
    # of prime number and perfect square
    if (flag):
        print("Yes")
    else:
        print("No")
 
# Driver Code
if __name__ == "__main__":
 
    N = 27
     
    sumOfPrimeSquare(N)
     
# This code is contributed by AnkThon
输出:
Yes

时间复杂度: O(N * log(log(N)))
辅助空间: O(N)