# Nth Magical Number in C++

A number is said to be a magical number, if that number is divisible by A or B. We have to find the Nth magical number. As the answer may very large, we will return it modulo 10^9 + 7.

So, if the input is like N = 4, A = 4, B = 3, then the output will be 8

To solve this, we will follow these steps −

• Define a function cnt(), this will take x, A, B,

• return (x / A) + (x / B) - (x / lcm of A and B)

• From the main method, do the following −

• l := 2, r := 1^14, ret := 0

• while l <= r, do −

• mid := l + (r - l) / 2

• k := cnt(mid, A, B)

• if k < N, then −

• l := mid + 1

• otherwise −

• ret := mid

• r := mid - 1

• ret := ret mod (10^9 + 7)

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const lli MOD = 1e9 + 7;
class Solution {
public:
int gcd(int a, int b) { return !b ? a : gcd(b, a % b); }
int lcm(int a, int b) { return (a * b) / gcd(a, b); }
lli cnt(lli x, lli A, lli B) {
return (x / A) + (x / B) - (x / lcm(A, B));
}
int nthMagicalNumber(int N, int A, int B) {
lli l = 2;
lli r = 1e14;
lli ret = 0;
while (l <= r) {
lli mid = l + (r - l) / 2;
lli k = cnt(mid, A, B);
if (k < N) {
l = mid + 1;
} else {
ret = mid;
r = mid - 1;
}
}
ret %= MOD;
return ret;
}
};
main(){
Solution ob;
cout << (ob.nthMagicalNumber(4, 4, 3));
}

## Input

4, 4, 3

## Output

8
Published on 04-Jun-2020 08:38:43