LeetCode878. Nth Magical Number

文章目录

一、题目

A positive integer is magical if it is divisible by either a or b.

Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: n = 1, a = 2, b = 3
Output: 2
Example 2:

Input: n = 4, a = 2, b = 3
Output: 6

Constraints:

1 <= n <= 109
2 <= a, b <= 4 * 104

二、题解

最大公约数,同余定理,二分答案。

class Solution {
   
public:
    int nthMagicalNumber(int n, int a, int b) {
   
        int mod = 1e9 + 7;
        long long lcm = a / gcd(a,b) * b;
        long long res = 0;
        long long l = 0,r = (long long)n * min(a,b);
        while(l <= r){
   
            long long mid = (l + r) / 2;
            if(mid / a + mid / b - mid / lcm >= n){
   
                res = mid;
                r = mid - 1;
            }
            else{
   
                l = mid + 1;
            }
        }
        return res % mod;
    }
};

相关推荐

  1. LeetCode878. Nth Magical Number

    2024-01-13 01:54:02       54 阅读
  2. LeetCode //C - 875. Koko Eating Bananas

    2024-01-13 01:54:02       49 阅读
  3. LeetCode879. Profitable Schemes——动态规划

    2024-01-13 01:54:02       51 阅读
  4. leetcode876-Middle of the Linked List

    2024-01-13 01:54:02       30 阅读
  5. leetcode88-Merge Sorted Array

    2024-01-13 01:54:02       42 阅读
  6. LeetCode //C - 87. Scramble String

    2024-01-13 01:54:02       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-13 01:54:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-13 01:54:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-13 01:54:02       87 阅读
  4. Python语言-面向对象

    2024-01-13 01:54:02       96 阅读

热门阅读

  1. vue3中el-table实现表格合计行

    2024-01-13 01:54:02       66 阅读
  2. [ECE]1.3 Basic logic operations

    2024-01-13 01:54:02       48 阅读
  3. 3 微信小程序

    2024-01-13 01:54:02       51 阅读
  4. 面试题-回溯算法解法模板

    2024-01-13 01:54:02       55 阅读
  5. 数据库面经---10则

    2024-01-13 01:54:02       61 阅读
  6. Android实现通过字符串找到图片、Class

    2024-01-13 01:54:02       49 阅读
  7. [ECE] Introduction to Digital Logic and Systems

    2024-01-13 01:54:02       52 阅读
  8. 【PHP】判断字符串是否是有效的base64编码

    2024-01-13 01:54:02       56 阅读
  9. golang中context详解

    2024-01-13 01:54:02       57 阅读