Sort an array in increasing order of their Multiplicative Persistence | C ++ program for the above approach ; Function to find the number of steps required to reduce a given number to a single - digit number ; Stores the required result ; Iterate until a single digit number is not obtained ; Store the number in a temporary variable ; Iterate over all digits and store their product in num ; Increment the answer by 1 ; Return the result ; Comparator function to sort the array ; Count number of steps required to reduce X and Y into single digits integer ; Return true ; Function to sort the array according to the number of steps required to reduce a given number into a single digit number ; Sort the array using the comparator function ; Print the array after sorting ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countReduction ( int num ) { int ans = 0 ; while ( num >= 10 ) { int temp = num ; num = 1 ; while ( temp > 0 ) { int digit = temp % 10 ; temp = temp / 10 ; num *= digit ; } ans ++ ; } return ans ; } bool compare ( int x , int y ) { int x1 = countReduction ( x ) ; int y1 = countReduction ( y ) ; if ( x1 < y1 ) return true ; return false ; } void sortArray ( int a [ ] , int n ) { sort ( a , a + n , compare ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 39 , 999 , 4 , 9876 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArray ( arr , N ) ; return 0 ; }