质因数分解

质因数分解

Fri Oct 04 2024
zzcoe
3 分钟

0躲炮弹 - 蓝桥云课 (lanqiao.cn)

CPP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

long get(long count, int l) {
    vector<long> list;
    long n = count;
    while (n % 2 == 0) {
        list.push_back(2);
        n /= 2;
    }
    for (long i = 3; i <= sqrt(n); i += 2) {
        while (n % i == 0) {
            list.push_back(i);
            n /= i;
        }
    }
    if (n > 2) {
        list.push_back(n);
    }

    if (list.size() == 1) {
        return count;//是质数
    } else {
        for (long aLong : list) {
            if (count / aLong < l) {
                return count;//最大的因数小于l,那他不可能是l到r之间的数的倍数
            } else {
                break;
            }
        }
    }
    return -1;
}

int main() {
    int n, l, r;
    cin >> n >> l >> r;

    if (n < l) {
        cout << 0 << endl;
        return 0;
    }
    if (n == l) {
        cout << 1 << endl;
        return 0;
    }

    long res = 0, count = max(n, r + 1);
    while (true) {
        long l1 = get(count, l);
        if (l1 != -1) {//count是质数或满足条件
            res = count - n;//到n的距离
            break;
        }
        count++;
    }

    count = n - 1;
    while (count > r) {//如果n大于r,判断r到n之间的数
        long l1 = get(count, l);
        if (l1 != -1) {
            res = min(n - count, res);
            break;
        }
        count--;
    }
    cout << min(res, static_cast<long>(n - l + 1)) << endl;
    return 0;
}