mathematical problems(数论)

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.

InputThere 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.OutputOutput 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.
题意:这就是求一个数可以拆分成多个数的和,然后求这多个数的最小公倍数的最大值,然后在取余于m;
解题思路:首先这是数论专题,肯定得结合数论的知识来求解,又由于是求最小公倍数的最大值(最什么最什么)符合之前的dp类型,可以将这道题看成一个背包dp,而且是完全背包的类型,s就为背包的容量;那要如何才能找到最小公倍数的最大值呢?那就是再分成的数上面有关,由于当分成的数全部都满足互质时,那么他们的最小公倍数就为他们的乘积,这应该时在找最大值时,那些数得满足的条件;
解题步骤
1)首先将范围内的全部素数找出来,储存在一个数组内,因为选的数的就在其中;
2)利用完全背包dp,找出如何组合可以是最小公倍数最大;
3)利用乘积可以转化成log的加法,这样防止太大溢出;

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
#define maxn 3005
bool judge[maxn];
int ss[maxn],num;
int ans[maxn];
double dp[maxn];
void init()
{
    memset(judge,true,sizeof(judge));
    num=0;
    judge[0]=judge[1]=false;
    for(int i=2;i<maxn;i++)
        {
            if(judge[i])
                {
                    ss[num]=i;
                    num++;
                    for(int j=i+i;j<maxn;j+=i)
                        judge[j]=false;
                }
        }
}
int main()
{
    init();
    int s,m;
    while(~scanf("%d%d",&s,&m))
        {
            memset(dp,0,sizeof(dp));
            for(int i=0;i<=s;i++)
                 ans[i]=1;
            for(int i=0;i<num&&ss[i]<=s;i++)
                {
                    double cnt=log(ss[i]*1.0);
                    for(int j=s;j>=ss[i];j--)
                        {
                            for(int k=1,p=ss[i];p<=j;k++,p*=ss[i])
                            {
                                if(dp[j-p]+cnt*k>dp[j])
                                    {
                                        dp[j]=dp[j-p]+cnt*k;
                                        ans[j]=ans[j-p]*p%m;
                                    }
                            }
                        }
                }
            cout<<ans[s]<<endl;
        }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值