ugly number code in c 2b 2b

Solutions on MaxInterview for ugly number code in c 2b 2b by the best coders in the world

showing results for - "ugly number code in c 2b 2b"
Leah
09 Nov 2017
1# include<iostream>
2using namespace std;
3int min(int x, int y, int z){ //find smallest among three numbers
4   if(x < y){
5      if(x < z)
6         return x;
7      else
8         return z;
9   }
10   else{
11      if(y < z)
12         return y;
13      else
14         return z;
15   }
16}
17int getUglyNum(int n){
18   int uglyNum[n]; // To store ugly numbers
19   int i2 = 0, i3 = 0, i5 = 0;
20   //find next multiple as 1*2, 1*3, 1*5
21   int next2mul = 2;
22   int next3mul = 3;
23   int next5mul = 5;
24   int next = 1; //initially the ugly number is 1
25   uglyNum[0] = 1;
26   for (int i=1; i<n; i++){
27      next = min(next2mul, next3mul, next5mul); //find next ugly number
28      uglyNum[i] = next;
29      if (next == next2mul){
30         i2++; //increase iterator of ugly numbers whose factor is 2
31         next2mul = uglyNum[i2]*2;
32      }
33      if (next == next3mul){
34         i3++; //increase iterator of ugly numbers whose factor is 3
35         next3mul = uglyNum[i3]*3;
36      }
37      if (next == next5mul){
38         i5++; //increase iterator of ugly numbers whose factor is 5
39         next5mul = uglyNum[i5]*5;
40      }
41   }
42   return next; //the nth ugly number
43}
44int main(){
45   int n;
46   cout << "Enter term: "; cin >> n;
47   cout << n << "th Ugly number is: " << getUglyNum(n)<< endl;
48}