Check if a number can be expressed as sum of two Perfect powers

Given a positive number N, the task is to check whether the given number N can be expressed in the form of ax + by where x and y > 1 and a and b > 0. If N can be expressed in the given form then print true otherwise print false.

Examples:

Input:  N = 5
Output: true
Explanation:
5 can be expressed as 22+12 

Input: N = 15
Output: false

Approach: The idea is to use the concept of perfect powers to determine whether the sum exists or not. Below are the steps:



  1. Create an array(say perfectPower[]) to store the numbers which are a perfect power or not.
  2. Now the array perfectPower[] store all the elements which are perfect power, therefore we generate all possible pair sum of all the elements in this array.
  3. Keep the mark of the sum calculated in the above step in an array isSum[] as it can be expressed in the form of ax + by .
  4. After the above steps if isSum[N] is true then print true otherwise print false.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function that returns true if n
// can be written as a^m+b^n
bool isSumOfPower(int n)
{
    // Taking isSum boolean array
    // for check the sum exist or not
    bool isSum[n + 1];
  
    // To store perfect squares
    vector<int> perfectPowers;
  
    perfectPowers.push_back(1);
  
    for (int i = 0; i < (n + 1); i++) {
  
        // Initally all sums as false
        isSum[i] = false;
    }
  
    for (long long int i = 2;
         i < (n + 1); i++) {
  
        if (isSum[i] == true) {
  
            // If sum exist then push
            // that sum into perfect
            // square vector
            perfectPowers.push_back(i);
            continue;
        }
  
        for (long long int j = i * i;
             j > 0 && j < (n + 1);
             j *= i) {
            isSum[j] = true;
        }
    }
  
    // Mark all perfect powers as false
    for (int i = 0;
         i < perfectPowers.size(); i++) {
        isSum[perfectPowers[i]] = false;
    }
  
    // Traverse each perfectPowers
    for (int i = 0;
         i < perfectPowers.size(); i++) {
  
        for (int j = i;
             j < perfectPowers.size(); j++) {
  
            // Calculating Sum with
            // perfect powers array
            int sum = perfectPowers[i]
                      + perfectPowers[j];
  
            if (sum < (n + 1))
                isSum[sum] = true;
        }
    }
    return isSum[n];
}
  
// Driver Code
int main()
{
    // Given Number n
    int n = 9;
  
    // Function Call
    if (isSumOfPower(n)) {
        cout << "true\n";
    }
    else {
        cout << "false\n";
    }
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
  
class GFG{
  
// Function that returns true if n
// can be written as a^m+b^n
static boolean isSumOfPower(int n)
{
      
    // Taking isSum boolean array
    // for check the sum exist or not
    boolean []isSum = new boolean[n + 1];
  
    // To store perfect squares
    Vector<Integer> perfectPowers = new Vector<Integer>();
  
    perfectPowers.add(1);
  
    for(int i = 0; i < (n + 1); i++)
    {
          
        // Initally all sums as false
        isSum[i] = false;
    }
  
    for(int i = 2; i < (n + 1); i++)
    {
        if (isSum[i] == true)
        {
              
            // If sum exist then push
            // that sum into perfect
            // square vector
            perfectPowers.add(i);
            continue;
        }
  
        for(int j = i * i; 
                j > 0 && j < (n + 1); 
                j *= i)
        {
            isSum[j] = true;
        }
    }
  
    // Mark all perfect powers as false
    for(int i = 0;
            i < perfectPowers.size(); 
            i++)
    {
        isSum[perfectPowers.get(i)] = false;
    }
  
    // Traverse each perfectPowers
    for(int i = 0
            i < perfectPowers.size();
            i++) 
    {
        for(int j = i; 
                j < perfectPowers.size(); 
                j++)
        {
              
            // Calculating Sum with
            // perfect powers array
            int sum = perfectPowers.get(i) + 
                      perfectPowers.get(j);
  
            if (sum < (n + 1))
                isSum[sum] = true;
        }
    }
    return isSum[n];
}
  
// Driver Code
public static void main(String[] args)
{
      
    // Given number n
    int n = 9;
  
    // Function call
    if (isSumOfPower(n))
    {
        System.out.print("true\n");
    }
    else 
    {
        System.out.print("false\n");
    }
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
  
# Function that returns true if n
# can be written as a^m+b^n
def isSumOfPower(n):
      
    # Taking isSum boolean array
    # for check the sum exist or not
    isSum = [0] * (n + 1)
  
    # To store perfect squares
    perfectPowers = []
  
    perfectPowers.append(1)
  
    for i in range(n + 1):
  
        # Initally all sums as false
        isSum[i] = False
      
    for i in range(2, n + 1):
        if (isSum[i] == True):
  
            # If sum exist then push
            # that sum into perfect
            # square vector
            perfectPowers.append(i)
            continue
          
        j = i * i
        while(j > 0 and j < (n + 1)):
            isSum[j] = True
            j *= i
          
    # Mark all perfect powers as false
    for i in range(len(perfectPowers)):
        isSum[perfectPowers[i]] = False
      
    # Traverse each perfectPowers
    for i in range(len(perfectPowers)):
        for j in range(len(perfectPowers)):
  
            # Calculating Sum with
            # perfect powers array
            sum = (perfectPowers[i] + 
                   perfectPowers[j])
  
            if (sum < (n + 1)):
                isSum[sum] = True
          
    return isSum[n]
  
# Driver Code
  
# Given Number n
n = 9
  
# Function call
if (isSumOfPower(n)):
    print("true")
else:
    print("false")
  
# This code is contributed by sanjoy_62

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function that returns true if n
// can be written as a^m+b^n
static bool isSumOfPower(int n)
{
      
    // Taking isSum bool array
    // for check the sum exist or not
    bool []isSum = new bool[n + 1];
  
    // To store perfect squares
    List<int> perfectPowers = new List<int>();
  
    perfectPowers.Add(1);
  
    for(int i = 0; i < (n + 1); i++)
    {
          
        // Initally all sums as false
        isSum[i] = false;
    }
  
    for(int i = 2; i < (n + 1); i++)
    {
        if (isSum[i] == true)
        {
              
            // If sum exist then push
            // that sum into perfect
            // square vector
            perfectPowers.Add(i);
            continue;
        }
  
        for(int j = i * i; 
                j > 0 && j < (n + 1); 
                j *= i)
        {
            isSum[j] = true;
        }
    }
  
    // Mark all perfect powers as false
    for(int i = 0;
            i < perfectPowers.Count; 
            i++)
    {
        isSum[perfectPowers[i]] = false;
    }
  
    // Traverse each perfectPowers
    for(int i = 0; 
            i < perfectPowers.Count;
            i++) 
    {
        for(int j = i; 
                j < perfectPowers.Count; 
                j++)
        {
              
            // Calculating Sum with
            // perfect powers array
            int sum = perfectPowers[i] + 
                      perfectPowers[j];
  
            if (sum < (n + 1))
                isSum[sum] = true;
        }
    }
    return isSum[n];
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // Given number n
    int n = 9;
  
    // Function call
    if (isSumOfPower(n))
    {
        Console.Write("true\n");
    }
    else
    {
        Console.Write("false\n");
    }
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


Output: 

true

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.