Perfect power (1, 4, 8, 9, 16, 25, 27, …)
A perfect power is a number that can be expressed as power of another positive integer.
Given a number n, find count of numbers from 1 to n that are of type xy where x >= 1 and y > 1
Examples :
Input : n = 10 Output : 4 1 4 8 and 9 are the numbers that are of form x ^ y where x > 0 and y > 1 Input : n = 50 Output : 10
A simple solution is to go through all powers of numbers from i = 2 to square root of n.
- C++
- Java
- Python3
- C#
- PHP
- Javascript
C++
// CPP program to count number of numbers from // 1 to n are of type x^y where x>0 and y>1 #include <bits/stdc++.h> using namespace std; // For our convenience #define ll long long // Function that keeps all the odd power // numbers upto n int powerNumbers( int n) { // v is going to store all power numbers vector< int > v; v.push_back(1); // Traverse through all base numbers and // compute all their powers smaller than // or equal to n. for (ll i = 2; i * i <= n; i++) { ll j = i * i; v.push_back(j); while (j * i <= n) { v.push_back(j * i); j = j * i; } } // Remove all duplicates sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); return v.size(); } int main() { cout << powerNumbers(50); return 0; } |
Java
Python3
C#
PHP
Javascript
Output:
10
Efficient Solution
We divide output set into subsets.
Even Powers: Simply we need to square root n. The count of even powers smaller than n is square root of n. For example even powers smaller than 25 are (1, 4, 9, 16 and 25).
Odd Powers: We modify above function to consider only odd powers.
- C++
- Java
- Python3
- C#
- PHP
- Javascript
C++
// C++ program to count number of numbers from // 1 to n are of type x^y where x>0 and y>1 #include <bits/stdc++.h> using namespace std; // For our convenience #define ll long long // Function that keeps all the odd power // numbers upto n int powerNumbers( int n) { vector< int > v; for (ll i = 2; i * i * i <= n; i++) { ll j = i * i; while (j * i <= n) { j *= i; // We need exclude perfect // squares. ll s = sqrt (j); if (s * s != j) v.push_back(j); } } // sort the vector sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); // Return sum of odd and even powers. return v.size() + (ll) sqrt (n); } int main() { cout << powerNumbers(50); return 0; } |
Java
Python3
C#
PHP
Javascript
Output :
10