Find the Nth Mosaic number
Given an integer N, the task is to find the Nth Mosaic number. A Mosaic number can be expressed as follows:
If N = Aa * Bb * Cc … where A, B, C.. are the prime factors of N then the Nth Mosaic number will be A * a * B * b * C * c ….
Examples:
Input: N = 8
Output: 6
8 can be expressed as 23.
So, the 8th Mosaic number will be 2 * 3 = 6
Input: N = 36
Output: 24
36 can be expressed as 22 * 32.
2 * 2 * 3 * 2 = 24
Approach: We have to find all the prime factors and also the powers of the factors in the number by dividing the number by the factor until the factor divides the number. The Nth Mosaic number will then be the product of the found prime factors and their powers.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int mosaic( int n)
{
int i, ans = 1;
for (i = 2; i <= n; i++) {
if (n % i == 0 && n > 0) {
int count = 0;
while (n % i == 0) {
n /= i;
count++;
}
ans *= count * i;
}
}
return ans;
}
int main()
{
int n = 36;
cout << mosaic(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int mosaic( int n)
{
int i, ans = 1 ;
for (i = 2 ; i <= n; i++)
{
if (n % i == 0 && n > 0 )
{
int count = 0 ;
while (n % i == 0 )
{
n /= i;
count++;
}
ans *= count * i;
}
}
return ans;
}
public static void main (String[] args)
{
int n = 36 ;
System.out.println (mosaic(n));
}
}
|
Python3
def mosaic(n):
i = 0
ans = 1
for i in range ( 2 ,n + 1 ):
if (n % i = = 0 and n > 0 ):
count = 0
while (n % i = = 0 ):
n / / = i
count + = 1
ans * = count * i
return ans
n = 36
print (mosaic(n))
|
C#
using System;
class GFG
{
static int mosaic( int n)
{
int i, ans = 1;
for (i = 2; i <= n; i++)
{
if (n % i == 0 && n > 0)
{
int count = 0;
while (n % i == 0)
{
n /= i;
count++;
}
ans *= count * i;
}
}
return ans;
}
static public void Main ()
{
int n = 36;
Console.WriteLine(mosaic(n));
}
}
|
Javascript
<script>
function mosaic(n)
{
let i, ans = 1;
for (i = 2; i <= n; i++)
{
if (n % i == 0 && n > 0)
{
let count = 0;
while (n % i == 0)
{
n = parseInt(n / i, 10);
count++;
}
ans *= count * i;
}
}
return ans;
}
let n = 36;
document.write(mosaic(n));
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...