Open In App

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

Last Updated : 13 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a positive integer n, the task is to check whether 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 "Yes", otherwise print "No".

Examples:

Input:  n = 5
Output: Yes
Explanation: 5 can be expressed as 22 + 12 

Input: n = 15
Output: No
Explanation: No possible combination can be formed.

Input:  n = 100
Output: Yes
Explanation: 100 can be expressed as 102 + 02 

Approach:

  • Generate all possible power of all the numbers from 2 to square root of n. We generate powers while value of the power is less than n.
  • Store those numbers in a hash set pows.
  • Now for each number x in pows, check if n - x exists, if so, print "Yes", otherwise check for all other numbers. If no such pair is found, print "No".

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find whether the number
// can be expressed in the form of
// the sum of two perfect powers
bool perfectPowerSum(int n) {
  
    // Stores all possible powers in a set
    unordered_set<int> pows;
    pows.insert(0);
    pows.insert(1);

    // Iterate over all possible bases
    for (int base = 2; base * base <= n; base++) {
        int power = base * base;
        while (power <= n) {
            pows.insert(power);
          
            // Prevent integer overflow
            if (power > (n / base)) break;
            power *= base;
        }
    }

    // Check if any two values sum up to n
    for (int x : pows) {
        if (pows.count(n - x)) {
            return true;
        }
    }
    return false;
}

int main() {
    int n = 100;
    if (perfectPowerSum(n)) 
        cout << "Yes";
    else 
        cout << "No";
    return 0;
}
Java
import java.util.*;

class GFG {

    // Function to find whether the number
    // can be expressed in the form of
    // the sum of two perfect powers
    static boolean perfectPowerSum(int n) {
      
        // Stores all possible powers in a set
        HashSet<Integer> pows = new HashSet<>();
        pows.add(0);
        pows.add(1);

        // Iterate over all possible bases
        for (int base = 2; base * base <= n; base++) {
            int power = base * base;
            while (power <= n) {
                pows.add(power);
              
                // Prevent integer overflow
                if (power > (n / base)) break;
                power *= base;
            }
        }

        // Check if any two values sum up to n
        for (int x : pows) {
            if (pows.contains(n - x)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int n = 100;
        if (perfectPowerSum(n)) 
            System.out.println("Yes");
        else 
            System.out.println("No");
    }
}
Python
# Function to find whether the number
# can be expressed in the form of
# the sum of two perfect powers
def perfectPowerSum(n):

    # Stores all possible powers in a set
    pows = set()
    pows.add(0)
    pows.add(1)

    # Iterate over all possible bases
    base = 2
    while base * base <= n:
        power = base * base
        while power <= n:
            pows.add(power)
            
            # Prevent integer overflow
            if power > (n // base):
                break
            power *= base
        base += 1

    # Check if any two values sum up to n
    for x in pows:
        if (n - x) in pows:
            return True
    return False

n = 100
if perfectPowerSum(n):
    print("Yes")
else:
    print("No")
C#
using System;
using System.Collections.Generic;

class GFG {

    // Function to find whether the number
    // can be expressed in the form of
    // the sum of two perfect powers
    static bool perfectPowerSum(int n) {
      
        // Stores all possible powers in a set
        HashSet<int> pows = new HashSet<int>();
        pows.Add(0);
        pows.Add(1);

        // Iterate over all possible bases
        for (int baseNum = 2; baseNum * baseNum <= n; baseNum++) {
            int power = baseNum * baseNum;
            while (power <= n) {
                pows.Add(power);
              
                // Prevent integer overflow
                if (power > (n / baseNum)) break;
                power *= baseNum;
            }
        }

        // Check if any two values sum up to n
        foreach (int x in pows) {
            if (pows.Contains(n - x)) {
                return true;
            }
        }
        return false;
    }

    static void Main() {
        int n = 100;
        if (perfectPowerSum(n)) 
            Console.WriteLine("Yes");
        else 
            Console.WriteLine("No");
    }
}
JavaScript
// Function to find whether the number
// can be expressed in the form of
// the sum of two perfect powers
function perfectPowerSum(n) {
  
    // Stores all possible powers in a set
    let pows = new Set();
    pows.add(0);
    pows.add(1);

    // Iterate over all possible bases
    for (let base = 2; base * base <= n; base++) {
        let power = base * base;
        while (power <= n) {
            pows.add(power);
          
            // Prevent integer overflow
            if (power > Math.floor(n / base)) break;
            power *= base;
        }
    }

    // Check if any two values sum up to n
    for (let x of pows) {
        if (pows.has(n - x)) {
            return true;
        }
    }
    return false;
}

let n = 100;
if (perfectPowerSum(n)) 
    console.log("Yes");
else 
    console.log("No");

Output
Yes

Time Complexity: O(n), the time complexity to calculate all the perfect powers less than or equal to n is ~O(log n). And to find the pairs, the time complexity is O(n). Thus the total complexity will be O(log n) + O(n) ~= O(n)
Auxiliary Space: O(n), to store the perfect powers less than or equal to n.


Next Article
Practice Tags :

Similar Reads