题目:
Least common multiple
Partychen like to do mathematical problems. One day, when he was doing on a least common multiple(LCM) problem, he suddenly thought of a very interesting question: if given a number of S, and we divided S into some numbers , then what is the largest LCM of these numbers? partychen thought this problems for a long time but with no result, so he turned to you for help!
Since the answer can very big,you should give the answer modulo M.
Input
There are many groups of test case.On each test case only two integers S( 0 < S <= 3000) and M( 2<=M<=10000) as mentioned above.
Output
Output the largest LCM modulo M of given S.
Sample Input
6 23
Sample Output
6
Hint: you can divied 6 as 1+2+3 and the LCM(1,2,3)=6 is the largest so we output 6%23=6.
题目链接:
https://vjudge.net/problem/HDU-3092
分析:
1、经分析,加数只能是互质的,而且加数本身一定是素数的幂。因此该问题转化为完全背包问题,由于每个加数只能是某一次幂(如果2是加数,则4,8,16,32等通通不能出现,不然就不是互质的了),所以滚动数组应该倒序扫描。
2、为了存储最小公倍数这个大数,又能用于不断地比较,我开了两个数组,一个是res[],存储最小公倍数的模数,一个是用于比较的double类型的dp[],dp[] = log10(res[]);
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 3010;
int s, mod;
int p[maxn];
vector<int> prime;
long long res[maxn];//save res % mod
double dp[maxn];///save log(res) which is used to compare the big data;
void chart()
{
for (int i = 2; i <= maxn; i++)
if (!p[i])
for (int j = i * 2; j <= maxn; j += i)
p[j] = 1;
for (int i = 2; i <= maxn; i++)
if (!p[i])
prime.push_back(i);
return;
}
int main()
{
chart();
while (cin >> s >> mod)
{
for (int i = 0; i < maxn; i++)
dp[i] = 0.0, res[i] = 1;
for(int k = 0; k < prime.size(); k++)
for(int i = s; i >= prime[k]; i--)
for(int j = prime[k]; i - j >= 0; j *= prime[k])
if (dp[i - j] + log10(j) > dp[i])
{
dp[i] = dp[i - j] + log10(j);
res[i] = res[i - j] * j % mod;
}
cout << res[s] << endl;
}
return 0;
}