Check if a number can be represented as a sum of a Prime Number and a Perfect Square
Last Updated :
23 Jul, 2025
Given a positive integer N, the task is to check if N can be represented as a sum of a Prime Number and a Perfect Square or not. If it is possible to represent N in required form, then print "Yes". Otherwise, print "No".
Examples:
Input: N = 27
Output: Yes
Explanation: 27 can be expressed as sum of 2 (prime) and 25 (perfect square).
Input: N = 64
Output: No
Naive Approach: The simplest approach to solve the given problem is to store all perfect squares which are less than or equal to N in an array. For every perfect square in the array, say X, check if (N - X) is a prime number or not. If found to be true, then print "Yes". Otherwise, print "No".
Algorithm:
- Create a function isPrime(n) that accepts an integer n as input and returns true if the supplied number is prime, otherwise false.
- Inside the isPrime(n) :
- If the given number n is less than or equal to 1, return false as it is not a prime number.
- Return true if the given number n is a prime number and is less than or equal to 3.
- If the number n is not a prime number and is divisible by 2 or 3, return false.
- Repeat this process for each 6th number in the range [5, sqrt(N)]. Return false if n is discovered to be non-prime. Otherwise, return true.
- Create a function sumOfPrimeSquare(n) that takes an integer n as input and returns nothing.
- Inside sumOfPrimeSquare(n) function.
- Initialize the integer variable i to 0
- Create squares ArrayList to hold all perfect squares with a size smaller than N.
- Place the ideal square in the squares ArrayList while i * i < n.
- Set a boolean variable flag's initial value to false.
- Go through each perfect square in the squares ArrayList iteratively:
- Put the perfect square difference from n in the difference variable.
- Update the flag to true and exit the loop if the difference is prime.
- Print "Yes" if N is the product of a prime number and a perfect square. Print "No" if not.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
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<int> 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<Integer> squares = new ArrayList<Integer>();
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
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to check if a
// number is prime or not
static 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
static void sumOfPrimeSquare(int n)
{
int i = 0;
// Stores all perfect
// squares less than N
List<int> squares = new List<int>();
while (i * i < n) {
// Store the perfect square
// in the array
squares.Add(i * i);
i++;
}
bool flag = false;
// Iterate over all perfect squares
for (i = 0; i < squares.Count; 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) {
Console.Write("Yes");
}
else
Console.Write("No");
}
// Driver Code
public static void Main()
{
int N = 27;
sumOfPrimeSquare(N);
}
}
// This code is contributed by ipg2016107.
JavaScript
<script>
// Javascript program for the above approach
// Function to check if a
// number is prime or not
function 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 || n % 3 == 0)
return false;
// Iterate over every 6 number
// from the range [5, sqrt(N)]
for(let 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
function sumOfPrimeSquare(n)
{
let i = 0;
// Stores all perfect
// squares less than N
let squares = [];
while (i * i < n)
{
// Store the perfect square
// in the array
squares.push(i * i);
i++;
}
let flag = false;
// Iterate over all perfect squares
for(i = 0; i < squares.length; i++)
{
// Store the difference of
// perfect square from n
let 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)
{
document.write("Yes");
}
else
document.write("No");
}
// Driver Code
let N = 27;
sumOfPrimeSquare(N);
// This code is contributed by rishavmahato348
</script>
Time Complexity: O(N)
Auxiliary Space: O(?N)
Efficient Approach: The above approach can be optimized by storing all the prime numbers smaller than N in an array, using Sieve of Eratosthenes. If there exists any prime number, say X, check if (N - X) is a perfect square or not. If found to be true, then print "Yes". Otherwise, print "No".
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
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;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to store all prime
// numbers less than or equal to N
static void SieveOfEratosthenes(boolean prime[],
int n)
{
// Update prime[0] and
// prime[1] as false
prime[0] = false;
prime[1] = false;
// Iterate over the range [2, Math.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
static void sumOfPrimeSquare(int n)
{
boolean flag = false;
// Stores all the prime numbers
// less than or equal to n
boolean []prime = new boolean[n + 1];
for(int i = 0; i < prime.length; i++)
prime[i] = true;
// 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 (Math.ceil((double)Math.sqrt(dif)) ==
Math.floor((double)Math.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)
{
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 29AjayKumar
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
C#
// C# program for the above approach
using System;
class GFG{
// Function to store all prime
// numbers less than or equal to N
static 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
static void sumOfPrimeSquare(int n)
{
bool flag = false;
// Stores all the prime numbers
// less than or equal to n
bool[] prime = new bool[n + 1];
Array.Fill(prime, true);
// 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 (Math.Ceiling((double)Math.Sqrt(dif)) ==
Math.Floor((double)Math.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)
{
Console.WriteLine("Yes");
}
else
Console.WriteLine("No");
}
// Driver Code
public static void Main()
{
int N = 27;
sumOfPrimeSquare(N);
}
}
// This code is contributed by ukasp
JavaScript
<script>
// Javascript program for the above approach
// Function to store all prime
// numbers less than or equal to N
function 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(let 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(let 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
function sumOfPrimeSquare(n)
{
let flag = false;
// Stores all the prime numbers
// less than or equal to n
let prime = new Array(n + 1).fill(true);
// Update the array prime[]
SieveOfEratosthenes(prime, n);
// Iterate over the range [0, n]
for(let i = 0; i <= n; i++)
{
// If current number
// is non-prime
if (!prime[i])
continue;
// Update difference
let dif = n - i;
// If difference is a
// perfect square
if (Math.ceil(Math.sqrt(dif)) ==
Math.floor(Math.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)
{
document.write("Yes");
}
else
document.write("No");
}
// Driver Code
let N = 27;
sumOfPrimeSquare(N);
// This code is contributed by subhammahato348
</script>
Time Complexity: O(N * log(log(N)))
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem