Uva 10791MininumSumLCM

  传送门     Uva10791

  给你一个数n,求至少两个正整数,使得他们的最小公倍数为n,输出最小的和 

 用到了唯一分解定理 ,详情见紫书第二版

 最近学了判断质数的MillerRabin 方法就用他了;

代码如下

#include <bits/stdc++.h>
using namespace std ;
typedef long long LL ;
LL mp[] = {2 , 7 , 61} ;

map<int , int > isp ; // 用map记录质因数和幂指数
LL qpow( LL a , LL b , LL n  ) // 快速幂取模
{
    LL ans = 1 ;
    for( ; b > 0 ; b >>= 1 , a = a*a%n )
        if( b&1 )  ans = ans * a%n  ;
    return ans ;
}
bool MillerRabin( LL  n ) // 把1当成特殊情况考虑,判断素数;
{
    if( n <= 2  )
        return true ;
    LL u = n-1 ;
    while ( u%2 == 0 ) u /= 2 ;
    LL tmp = u ;
    for( int i = 0 ; i < 3 && n > mp[i] ; i++ )
    {
        u = tmp ;
        LL x = qpow( mp[i] , u  , n ) ;
        while ( u < n )
        {
            LL y = qpow(x , 2 , n ) ;
            if(  y== 1 && x != 1 && x != n-1 )
                return false ;
            x = y ;
            u = u*2 ;
        }
        if ( x != 1 )
            return false ;
    }
    return true ;
}
LL pow ( int a , int b )  // 幂
{
    LL ans = 1 ;
    for( ; b > 0 ; b >>= 1 , a = a*a )
        if( b&1)  ans *= a ;
    return ans ;
}
int main( )
{
    LL n ;
    int cas = 0 ;
    while ( cin >> n && n != 0 )
    {
        ++cas ;
        printf( "Case %d: " , cas ) ;
        if( MillerRabin( n ) ) // 如果是素数和1就直接输出 这两个数是 ( n, 1 ),所以输出n+1;
        {
            cout << n+1 <<endl ;
            continue ;
        }
        int m = (int)sqrt(n+0.5) ;
        for( int i = 2 ; i <= m ; i++ )  if( n%i == 0 ) // 分解这个数,如果不是素数
            {
                while ( n%i == 0 )
                {
                    n/=i  ;
                    isp[i]++  ;
                }
                if( n > 1 && MillerRabin(n) )
                {
                    isp[n]++  ;
                    break ;
                }
            }
        LL ans = 0 ;
        map<int , int >::iterator it ;
        for( it = isp.begin( ) ;  it != isp.end( ) ; it++ )
            ans = ans + pow( it->first , it->second ) ;
        if( isp.size() <= 1 ) // 如果只有一个质因数,那么还用加个1 ,因为至少两个数
            cout << ans+1 <<endl ;
        else
            cout << ans <<endl ;
        isp.clear( ) ;
    }

    return 0 ;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值