Check if the number is a Prime power number - GeeksforGeeks

02 Mar, 2022
Given an integer N, the task is to check if the number is a Prime power number. If yes, then print the number along with its power which is equal to N. Else print -1. 
A prime power is a positive integer power of a single prime number. For example: 7 = 71, 9 = 32 and 32 = 25 are prime powers, while 6 = 2 × 3, 12 = 22 × 3 and 36 = 62 = 22 × 32 are not. (The number 1 is not counted as a prime power.)
Note: If there is no such prime number, print -1. 
Examples: 
Input: N = 49 Output: 72 Explanation: N can be represented as a power of prime number 7. N = 49 = 72
Input: N = 100 Output: -1 Explanation: N cannot be represented as a power of any prime number.
Approach: The idea is to use the Sieve of Eratosthenes to find all the prime numbers. Then, Iterate over all the prime numbers and check that if any prime number divides the given number N, if yes then divide it until it becomes 1 or not divisible by that prime number. Finally, check that the number is equal to 1, If yes then return the prime number otherwise given number cannot be expressed as a prime number raised to some power.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation to check if// a number is a prime power number#include<bits/stdc++.h>using namespace std; // Array to store the// prime numbersbool is_prime[1000001];vector<int> primes; // Function to mark the prime// numbers using Sieve of// Eratosthenesvoid SieveOfEratosthenes(int n){    int p = 2;         for(int i = 0; i < n; i++)       is_prime[i] = true;            while (p * p <= n)    {                 // If prime[p] is not        // changed, then it is a prime        if (is_prime[p] == true)        {                         // Update all multiples of p            for(int i = p * p; i < n + 1; i += p)            {               is_prime[i] = false;            }        }        p += 1;    }    for(int i = 2; i < n + 1; i++)    {       if (is_prime[i])           primes.push_back(i);    }} // Function to check if the// number can be represented// as a power of primepair<int, int> power_of_prime(int n){    for(auto i : primes)    {               if (n % i == 0)       {           int c = 0;           while(n % i == 0)           {               n /= i;               c += 1;           }           if(n == 1)              return {i, c};           else              return {-1, 1};       }    }} // Driver Code        int main(){    int n = 49;    SieveOfEratosthenes(int(sqrt(n)) + 1);         // Function Call    pair<int, int> p = power_of_prime(n);         if (p.first > 1)        cout << p.first << " ^ "             << p.second << endl;    else        cout << -1 << endl;} // This code is contributed by Surendra_Gangwar
// Java implementation to check if // a number is a prime power numberimport java.io.*;import java.util.*;import java.lang.Math; class GFG{ // Array to store the // prime numbers    static ArrayList<Integer> primes = new ArrayList<Integer>(); // Function to mark the prime // numbers using Sieve of // Eratosthenespublic static void sieveOfEratosthenes(int n){         // Create a boolean array "prime[0..n]" and initialize    // all entries it as true. A value in prime[i] will    // finally be false if i is Not a prime, else true.    boolean prime[] = new boolean[n + 1];         for(int i = 0; i < n; i++)        prime[i] = true;         for(int p = 2; p * p <= n; p++)    {                 // If prime[p] is not changed,        // then it is a prime        if(prime[p] == true)        {             // Update all multiples of p            for(int i = p * 2; i <= n; i += p)                prime[i] = false;        }    }         // Print all prime numbers    for(int i = 2; i <= n; i++)    {        if(prime[i] == true)            primes.add(i);    }} // Function to check if the // number can be represented // as a power of primepublic static int[] power_of_prime(int n){    for(int ii = 0; ii < primes.size(); ii++)    {        int i = primes.get(ii);                 if (n % i == 0)        {            int c = 0;            while(n % i == 0)            {                n /= i;                c += 1;            }                         if(n == 1)                return new int[]{i, c};            else                return new int[]{-1, 1};        }    }    return new int[]{-1, 1};} // Driver codepublic static void main(String args[]){    int n = 49;    int sq = (int)(Math.sqrt(n));    sieveOfEratosthenes(sq + 1);     // Function call    int arr[] = power_of_prime(n);     if (arr[0] > 1)        System.out.println(arr[0] + " ^ " + arr[1]);    else        System.out.println("-1");}} // This code is contributed by grand_master
# Python3 implementation to check# if a number is a prime power number from math import * # Array to store the# prime numbersis_prime = [True for i in range(10**6 + 1)]primes =[] # Function to mark the prime# numbers using Sieve of# Eratosthenesdef SieveOfEratosthenes(n):    p = 2    while (p * p <= n):        # If prime[p] is not        # changed, then it is a prime        if (is_prime[p] == True):            # Update all multiples of p            for i in range(p * p, n + 1, p):                is_prime[i] = False        p += 1    for i in range(2, n + 1):        if is_prime[i]:            primes.append(i) # Function to check if the# number can be represented# as a power of primedef power_of_prime(n):    for i in primes:        if n % i == 0:            c = 0            while n % i == 0:                n//= i                c += 1            if n == 1:                return (i, c)            else:                return (-1, 1) # Driver Code        if __name__ == "__main__":    n = 49    SieveOfEratosthenes(int(sqrt(n))+1)         # Function Call    num, power = power_of_prime(n)    if num > 1:        print(num, "^", power)    else:        print(-1)
// C# implementation to check if// a number is a prime power numberusing System;using System.Collections; class GFG{ // Array to store the// prime numbers    static ArrayList primes = new ArrayList(); // Function to mark the prime// numbers using Sieve of// Eratosthenespublic static void sieveOfEratosthenes(int n){         // Create a boolean array "prime[0..n]"    // and initialize all entries it as true.    // A value in prime[i] will finally be    // false if i is Not a prime, else true.    bool []prime = new bool[n + 1];         for(int i = 0; i < n; i++)        prime[i] = true;         for(int p = 2; p * p <= n; p++)    {                 // If prime[p] is not changed,        // then it is a prime        if (prime[p] == true)        {             // Update all multiples of p            for(int i = p * 2; i <= n; i += p)                prime[i] = false;        }    }         // Print all prime numbers    for(int i = 2; i <= n; i++)    {        if (prime[i] == true)            primes.Add(i);    }} // Function to check if the// number can be represented// as a power of primepublic static int[] power_of_prime(int n){    for(int ii = 0; ii < primes.Count; ii++)    {        int i = (int)primes[ii];                 if (n % i == 0)        {            int c = 0;            while (n % i == 0)            {                n /= i;                c += 1;            }                         if (n == 1)                return new int[]{i, c};            else                return new int[]{-1, 1};        }    }    return new int[]{-1, 1};} // Driver codepublic static void Main(string []args){    int n = 49;    int sq = (int)(Math.Sqrt(n));    sieveOfEratosthenes(sq + 1);     // Function call    int []arr = power_of_prime(n);     if (arr[0] > 1)        Console.Write(arr[0] + " ^ " +                      arr[1]);    else        Console.Write("-1");}} // This code is contributed by rutvik_56
<script> // Javascript implementation to check if// a number is a prime power number // Array to store the// prime numbers   let primes = [];  // Function to mark the prime// numbers using Sieve of// Eratosthenesfunction sieveOfEratosthenes(n){          // Create a boolean array "prime[0..n]"    // and initialize all entries it as true.    // A value in prime[i] will finally be    // false if i is Not a prime, else true.    let prime = Array.from({length: n+1}, (_, i) => 0);          for(let i = 0; i < n; i++)        prime[i] = true;          for(let p = 2; p * p <= n; p++)    {                  // If prime[p] is not changed,        // then it is a prime        if (prime[p] == true)        {              // Update all multiples of p            for(let i = p * 2; i <= n; i += p)                prime[i] = false;        }    }          // Print all prime numbers    for(let i = 2; i <= n; i++)    {        if (prime[i] == true)            primes.push(i);    }}  // Function to check if the// number can be represented// as a power of primefunction power_of_prime(n){    for(let ii = 0; ii < primes.length; ii++)    {        let i = primes[ii];                  if (n % i == 0)        {            let c = 0;            while (n % i == 0)            {                n /= i;                c += 1;            }                          if (n == 1)                return [i, c];            else                return [-1, 1];        }    }    return [-1, 1];}         // Driver Code             let n = 49;    let sq = (Math.sqrt(n));    sieveOfEratosthenes(sq + 1);      // Function call    let arr = power_of_prime(n);      if (arr[0] > 1)        document.write(arr[0] + " ^ " +                      arr[1]);    else        document.write("-1");     </script>
7 ^ 2
 
SURENDRA_GANGWAR
grand_master
rutvik_56
code_hunt
saurabh1990aror
sweetyty
maths-power
Prime Number
Competitive Programming
Mathematical
School Programming
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shortest path in a directed graph by Dijkstra’s algorithm
Breadth First Traversal ( BFS ) on a 2D array
Multistage Graph (Shortest Path)
Runtime Errors
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7