Sort given Array in descending order according to highest power of prime factors
Last Updated :
23 Jul, 2025
Given an array arr[] of size N. The task is to sort the elements in arr[] based to their Highest Degree of Expression, in descending order. The Highest Degree of a number is defined as the maximum value in which it can be expressed as the power of its factors.
Note:
- If the numbers have the same degree of expression the element coming first in the original array will come first in the sorted array.
- If two numbers have the same highest degree, then the First-Come-First-Serve approach should be used.
Examples:
Input: arr[] = {81, 25, 27, 32, 51}
Output: [32, 81, 27, 25, 51]
Explanation: After prime factorization
81 can be represented as 811, 92, or 34. For the highest degree of expression, choose (3)4 because 4 is greater than 2 and 1.
25 can be represented as 52.
27 can be represented as 33.
32 can be represented as 25.
51 can be represented as 511.
Now, sort them in descending order based on their power.
Therefore, 32 comes first since 25 has the highest power, followed by 81, 27, 25, and finally 51 with a power of 1.
Input: arr[] = {23, 6}
Output: [23, 6]
Explanation: Since 23 and 6 both have the same power(1), we print 23 which comes first, followed by 6.
Approach: This problem can be solved by using Prime Factorization. Follow the steps below to solve the given problem.
- The highest power of a number can be obtained by breaking it into a product of its prime factors.
- Choose the factor which has the highest power among those factors.
- Store the highest power of a number along with that number in a pair and sort that pair based on the highest power of its factors.
- Pre-compute all the prime numbers up to 10^5 using the Sieve of Eratosthenes method.
- For each number in the array, find all the factors of that number and store the highest power of its factor along with that number in a vector of pair of integers.
- Sort that pair in descending based on the second element(The Highest Order of Expression).
Below is the implementation of the above approach.
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
bitset<500001> Primes;
vector<int> Factors;
// Function to compute Sieve of Eratosthenes
void SieveOfEratosthenes(int n)
{
Primes[0] = 1;
for (int i = 3; i <= n; i += 2) {
if (Primes[i / 2] == 0) {
for (int j = 3 * i; j <= n; j += 2 * i)
Primes[j / 2] = 1;
}
}
for (int i = 2; i <= 500001; i++) {
if (!Primes[i])
Factors.push_back(i);
}
}
// Compare function for sorting
bool compare(const pair<int, int>& a,
const pair<int, int>& b)
{
return a.second > b.second;
}
// Function to find any log(a) base b
int log_a_to_base_b(int a, int b)
{
return log(a) / log(b);
}
// Function to find the Highest Power
// of K which divides N
int HighestPower(int N, int K)
{
int start = 0, end = log_a_to_base_b(N, K);
int ans = 0;
while (start <= end) {
int mid = start + (end - start) / 2;
int temp = (int)(pow(K, mid));
if (N % temp == 0) {
ans = mid;
start = mid + 1;
}
else {
end = mid - 1;
}
}
return ans;
}
// Function to display N numbers
// on the basis of their Highest Order
// of Expression in descending order
void displayHighestOrder(int arr[], int N)
{
vector<pair<int, int> > Nums;
for (int i = 0; i < N; i++) {
// The least power of a number
// will always be 1 because
// that number raised to
// the power 1 is it itself
int temp = 1;
for (auto& Prime : Factors) {
// The factor of a number greater than
// its square root is the number itself
// which is considered in temp
if (Prime * Prime > arr[i])
break;
else if (arr[i] % Prime == 0)
temp = max(
temp,
HighestPower(arr[i], Prime));
}
Nums.push_back(make_pair(arr[i], temp));
}
sort(Nums.begin(), Nums.end(), compare);
for (int i = 0; i < N; i++) {
cout << Nums[i].first << " ";
}
cout << endl;
}
// Driver Code
int main()
{
SieveOfEratosthenes(500000);
int arr[] = { 81, 25, 27, 32, 51 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
displayHighestOrder(arr, N);
return 0;
}
Java
import java.util.*;
public class GFG {
static boolean Primes[] = new boolean[500002];
static ArrayList<Integer> Factors = new ArrayList<>();
static class Pair {
int first;
int second;
Pair(int i, int j)
{
first = i;
second = j;
}
}
// Function to compute Sieve of Eratosthenes
static void SieveOfEratosthenes(int n)
{
Primes[0] = true;
for (int i = 3; i <= n; i += 2) {
if (!Primes[i / 2]) {
for (int j = 3 * i; j <= n; j += 2 * i)
Primes[j / 2] = true;
}
}
for (int i = 2; i <= 500001; i++) {
if (!Primes[i])
Factors.add(i);
}
}
// Function to find any log(a) base b
static int log_a_to_base_b(int a, int b)
{
return (int)(Math.log(a) / Math.log(b));
}
// Function to find the Highest Power
// of K which divides N
static int HighestPower(int N, int K)
{
int start = 0, end = log_a_to_base_b(N, K);
int ans = 0;
while (start <= end) {
int mid = start + (end - start) / 2;
int temp = (int)(Math.pow(K, mid));
if (N % temp == 0) {
ans = mid;
start = mid + 1;
}
else {
end = mid - 1;
}
}
return ans;
}
// Function to display N numbers
// on the basis of their Highest Order
// of Expression in descending order
static void displayHighestOrder(int arr[], int N)
{
List<Pair> Nums = new ArrayList<>();
for (int i = 0; i < N; i++) {
// The least power of a number
// will always be 1 because
// that number raised to
// the power 1 is it itself
int temp = 1;
for (int Prime : Factors) {
// The factor of a number greater than
// its square root is the number itself
// which is considered in temp
if (Prime * Prime > arr[i])
break;
else if (arr[i] % Prime == 0)
temp = Math.max(
temp, HighestPower(arr[i], Prime));
}
Nums.add(new Pair(arr[i], temp));
}
Collections.sort(Nums,
(a, b) -> b.second - a.second);
for (int i = 0; i < N; i++) {
System.out.print(Nums.get(i).first + " ");
}
System.out.println();
}
public static void main(String[] args)
{
SieveOfEratosthenes(500000);
int arr[] = { 81, 25, 27, 32, 51 };
int N = arr.length;
// Function Call
displayHighestOrder(arr, N);
}
}
// This code is contributed by aadityapburujwale.
Python3
# Python code for the above approach
import math as Math
Primes = [0] * 500001
Factors = []
# Function to compute Sieve of Eratosthenes
def SieveOfEratosthenes(n):
Primes[0] = 1
for i in range(3, n + 1, 2):
if (Primes[i // 2] == 0):
for j in range(3 * i, n + 1, 2 * i):
Primes[j // 2] = 1
for i in range(2, 500001) :
if (not Primes[i]):
Factors.append(i)
# Compare function for sorting
def compare(a, b):
return b.second - a.second
# Function to find any log(a) base b
def log_a_to_base_b(a, b):
return Math.log(a) / Math.log(b)
# Function to find the Highest Power
# of K which divides N
def HighestPower(N, K):
start = 0
end = log_a_to_base_b(N, K)
ans = 0
while (start <= end):
mid = start + Math.floor((end - start) / 2)
temp = (Math.pow(K, mid))
if (N % temp == 0):
ans = mid
start = mid + 1
else:
end = mid - 1
return ans
# Function to display N numbers
# on the basis of their Highest Order
# of Expression in descending order
def displayHighestOrder(arr, N):
Nums = []
for i in range(N):
# The least power of a number
# will always be 1 because
# that number raised to
# the power 1 is it itself
temp = 1
for Prime in Factors:
# The factor of a number greater than
# its square root is the number itself
# which is considered in temp
if (Prime * Prime > arr[i]):
break
elif (arr[i] % Prime == 0):
temp = max( temp, HighestPower(arr[i], Prime))
Nums.append({"first": arr[i], "second": temp})
Nums = sorted(Nums, key = lambda l: l["second"], reverse = True)
for i in range(N):
print(Nums[i]["first"], end = " ")
print('')
# Driver Code
SieveOfEratosthenes(500000)
arr = [81, 25, 27, 32, 51]
N = len(arr)
# Function Call
displayHighestOrder(arr, N)
# This code is contributed by gfgking.
C#
using System;
using System.Collections.Generic;
public class GFG {
static bool[] Primes = new bool[500002];
static List<int> Factors = new List<int>();
class Pair {
public int first;
public int second;
public Pair(int i, int j)
{
first = i;
second = j;
}
}
// Function to compute Sieve of Eratosthenes
static void SieveOfEratosthenes(int n)
{
Primes[0] = true;
for (int i = 3; i <= n; i += 2) {
if (!Primes[i / 2]) {
for (int j = 3 * i; j <= n; j += 2 * i)
Primes[j / 2] = true;
}
}
for (int i = 2; i <= 500001; i++) {
if (!Primes[i])
Factors.Add(i);
}
}
// Function to find any log(a) base b
static int log_a_to_base_b(int a, int b)
{
return (int)(Math.Log(a) / Math.Log(b));
}
// Function to find the Highest Power
// of K which divides N
static int HighestPower(int N, int K)
{
int start = 0, end = log_a_to_base_b(N, K);
int ans = 0;
while (start <= end) {
int mid = start + (end - start) / 2;
int temp = (int)(Math.Pow(K, mid));
if (N % temp == 0) {
ans = mid;
start = mid + 1;
}
else {
end = mid - 1;
}
}
return ans;
}
// Function to display N numbers
// on the basis of their Highest Order
// of Expression in descending order
static void displayHighestOrder(int[] arr, int N)
{
List<Pair> Nums = new List<Pair>();
for (int i = 0; i < N; i++) {
// The least power of a number
// will always be 1 because
// that number raised to
// the power 1 is it itself
int temp = 1;
foreach(int Prime in Factors)
{
// The factor of a number greater than
// its square root is the number itself
// which is considered in temp
if (Prime * Prime > arr[i])
break;
else if (arr[i] % Prime == 0)
temp = Math.Max(
temp, HighestPower(arr[i], Prime));
}
Nums.Add(new Pair(arr[i], temp));
}
Nums.Sort((a, b) = > b.second - a.second);
for (int i = 0; i < N; i++) {
Console.Write(Nums[i].first + " ");
}
Console.WriteLine();
}
static public void Main()
{
SieveOfEratosthenes(500000);
int[] arr = { 81, 25, 27, 32, 51 };
int N = arr.Length;
// Function Call
displayHighestOrder(arr, N);
}
}
// This code is contributed by akashish__
JavaScript
<script>
// JavaScript code for the above approach
let Primes = new Array(500001);
let Factors = [];
// Function to compute Sieve of Eratosthenes
function SieveOfEratosthenes(n) {
Primes[0] = 1;
for (let i = 3; i <= n; i += 2) {
if (Primes[(Math.floor(i / 2))] == 0) {
for (let j = 3 * i; j <= n; j += 2 * i)
Primes[(Math.floor(j / 2))] = 1;
}
}
for (let i = 2; i <= 500001; i++) {
if (!Primes[i])
Factors.push(i);
}
}
// Compare function for sorting
function compare(a,
b) {
return b.second - a.second;
}
// Function to find any log(a) base b
function log_a_to_base_b(a, b) {
return Math.log(a) / Math.log(b);
}
// Function to find the Highest Power
// of K which divides N
function HighestPower(N, K) {
let start = 0, end = log_a_to_base_b(N, K);
let ans = 0;
while (start <= end) {
let mid = start + Math.floor((end - start) / 2);
let temp = (Math.pow(K, mid));
if (N % temp == 0) {
ans = mid;
start = mid + 1;
}
else {
end = mid - 1;
}
}
return ans;
}
// Function to display N numbers
// on the basis of their Highest Order
// of Expression in descending order
function displayHighestOrder(arr, N) {
let Nums = [];
for (let i = 0; i < N; i++) {
// The least power of a number
// will always be 1 because
// that number raised to
// the power 1 is it itself
let temp = 1;
for (Prime of Factors) {
// The factor of a number greater than
// its square root is the number itself
// which is considered in temp
if (Prime * Prime > arr[i])
break;
else if (arr[i] % Prime == 0)
temp = Math.max(
temp,
HighestPower(arr[i], Prime));
}
Nums.push({ first: arr[i], second: temp });
}
Nums.sort(compare)
for (let i = 0; i < N; i++) {
document.write(Nums[i].first + " ");
}
document.write('<br>')
}
// Driver Code
SieveOfEratosthenes(500000);
let arr = [81, 25, 27, 32, 51];
let N = arr.length;
// Function Call
displayHighestOrder(arr, N);
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N1.5 *log(K)), Where K is the maximum element in the array.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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