1到n的的最小公倍數

代碼:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

static const int N = 100;

static string BigMulti(string &a, string &b)
{
    string ret;
    vector<int> v(a.length() + b.length() - 1, 0);
    for (int i = 0; i < a.length(); i++) {
        for (int j =0; j < b.length(); j++) {
            v[i + j] += (a[i] - '0') * (b[j] - '0');
        }
    }

    int upper = 0;
    int tmp;
    char c;
    for (int i = v.size() - 1; i >= 0; i--) {
        tmp = upper + v[i];
        c = (tmp % 10 + '0');
        ret = c + ret;
        upper = tmp / 10;
    }

    if (upper > 0) {
        ret = to_string(upper) + ret;
    }
    return ret;
}

// n >= 2 && n <= N
static string BiggestGongYueShuForNJieCheng(int n)
{
    string ret = "1";
    string str;
    vector<int> yinzi(N + 1, 0);
    yinzi[1] = 1;
    yinzi[2] = 2;
    int tmp;
    for (int i = 3; i <= N; i++) {
        tmp = i;
        for (int j = 2; j <= i - 1; j++) {
            if (tmp % yinzi[j] == 0) {
                tmp = tmp / yinzi[j];
                if (tmp == 1) {
                    break;
                }
            }
        }
        yinzi[i] = tmp;
    }

    for (int i = 2; i <= n; i++) {
        if (yinzi[i] == 1) {
            continue;
        }
        str = to_string(yinzi[i]);
        ret = BigMulti(ret , str);
    }
    return ret;
}

int main()
{
    string a = "1";
    string b = "1";
    cout << BigMulti(a, b) << endl;
    int n;
    cin >> n;
    cout << BiggestGongYueShuForNJieCheng(n) << endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章