|
| 1 | +// Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. |
| 2 | +// By convention, 1 is included. |
| 3 | +// A program to find the nth Ugly number |
| 4 | + |
| 5 | +// Algorithm : |
| 6 | +// Initialize three-pointers two, three, and five pointing to zero. |
| 7 | +// Take 3 variables nm2, nm3, and nm5 to keep track of next multiple of 2,3 and 5. |
| 8 | +// Make an array of size n to store the ugly numbers with 1 at 0th index. |
| 9 | +// Initialize a variable next which stores the value of the last element in the array. |
| 10 | +// Run a loop n-1 times and perform steps 6,7 and 8. |
| 11 | +// Update the values of nm2, nm3, nm5 as ugly[two]*2, ugly[three]*3, ugly[5]*5 respectively. |
| 12 | +// Select the minimum value from nm2, nm3, and nm5 and increment the pointer related to it. |
| 13 | +// Store the minimum value in variable next and array. |
| 14 | +// Return next. |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | +package Maths; |
| 19 | +import java.util.*; |
| 20 | +class NthUglyNumber { |
| 21 | + /* Function to get the nth ugly number*/ |
| 22 | + public long getNthUglyNo(int n) { |
| 23 | + long[] ugly = new long[n]; |
| 24 | + int two=0, three=0, five=0; |
| 25 | + long nm2=2, nm3=3, nm5=5; |
| 26 | + long next = 1; |
| 27 | + |
| 28 | + ugly[0] = 1; |
| 29 | + |
| 30 | + for(int i=1; i<n; i++){ |
| 31 | + next = Math.min(nm2, Math.min(nm3, nm5)); |
| 32 | + |
| 33 | + ugly[i] = next; |
| 34 | + if(next == nm2){ |
| 35 | + two = two+1; |
| 36 | + nm2 = ugly[two]*2; |
| 37 | + } |
| 38 | + if(next == nm3){ |
| 39 | + three = three+1; |
| 40 | + nm3 = ugly[three]*3; |
| 41 | + } |
| 42 | + if(next == nm5){ |
| 43 | + five = five+1; |
| 44 | + nm5 = ugly[five]*5; |
| 45 | + } |
| 46 | + } |
| 47 | + return next; |
| 48 | + } |
| 49 | + |
| 50 | + public static void main(String[] args) |
| 51 | + { |
| 52 | + Scanner sc = new Scanner(System.in); |
| 53 | + System.out.println("Enter the value of n : "); |
| 54 | + int n = sc.nextInt(); |
| 55 | + NthUglyNumber ob = new NthUglyNumber(); |
| 56 | + long ugly = ob.getNthUglyNo(n); |
| 57 | + System.out.println("nth Ugly number is : "+ugly); |
| 58 | + } |
| 59 | +} |
0 commit comments