Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ugly Number III in C++
Suppose we have to write a program to find the n-th ugly number. The Ugly numbers are positive integers which are divisible by a or b or c. So for example, if n = 3 and a = 2, b = 3 and c = 5, then the output will be 4, as the ugly numbers are [2,3,4,5,6,8,9,10], the third one is 4.
To solve this, we will follow these steps −
make a method called ok(), this will take x, a, b, c, this will act like below −
return (x/a) + (x/b) + (x/c) – (x/lcm(a,b)) - (x/lcm(b, c)) - (x/lcm(b,c)) - (x/lcm(a,c)) + (x/lcm(a, lcm(b,c)))
From the main method, do following −
low := 1, high := 2 * (10^9)
-
while low < high −
mid := low + (high - low) / 2
x := ok(mid, a, b, c)
if x >= n, then high := mid, otherwise low := mid + 1
return high
Example (C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
lli gcd(lli a, lli b){
return b == 0? a: gcd(b, a % b);
}
lli lcm(lli a, lli b){
return a * b / gcd(a, b);
}
lli ok(lli x, lli a, lli b, lli c){
return (x / a) + (x / b) + (x / c) - (x / lcm(a, b)) - (x / lcm(b, c)) - (x / lcm(a, c)) + (x / lcm(a, lcm(b, c)));
}
int nthUglyNumber(int n, int a, int b, int c) {
int low = 1;
int high = 2 * (int) 1e9;
while(low < high){
int mid = low + (high - low) / 2;
int x = ok(mid, a, b, c);
if(x>= n){
high = mid;
}
else low = mid + 1;
}
return high;
}
};
main(){
Solution ob;
cout << (ob.nthUglyNumber(3,2,3,5));
}
Input
3 2 3 5
Output
4