zoj Simple Equation 数论

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5176

AX+BY = XY  => (X-B)*(Y-A)= A*B

对A*B因式分解,这里不要乘起来,分A,B因式分解

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<cmath>
#include<sstream>
#include<queue>

#define MAXN 105000
#define PI acos(-1.0)
#define LL long long
#define REP(i,n) for(int i=0; i<n; i++)
#define FOR(i,s,t) for(int i=s; i<=t; i++)
#define show(x) { cerr<<">>>"<<#x<<" = "<<x<<endl; }
#define showtwo(x,y) { cerr<<">>>"<<#x<<"="<<x<<"  "<<#y<<" = "<<y<<endl; }
using namespace std;

LL A,B,X,Y,ansX,ansY,M;
int prime[MAXN],cnt; //生成质数表
LL sum_AB;
struct Factor
{
    int p,k; //p^k;
}a[15];
int pv;

void get_prime()
{
    bool flag[MAXN];
    memset(flag,0,sizeof(flag));
    cnt = 0;

    for(int i=2; i<MAXN; i++)
    {
        if(!flag[i])
        {
            prime[cnt++] = i;
            for(int j=i+i; j<MAXN; j+=i) flag[j] = true;
        }
    }
}

void factor_analysis(int c,int d)
{
    pv = 0;
    for(int i=0; i<cnt && (c||d); i++)
    {
        if(c%prime[i] == 0 || d%prime[i] == 0)
        {
            a[pv].p = prime[i];
            a[pv].k = 0;
            while(c % prime[i] == 0) a[pv].k++,c /= prime[i];
            while(d % prime[i] == 0) a[pv].k++,d /= prime[i];
            pv++;
        }
    }
    if(c != 1) a[pv].p = c,a[pv].k = 1,pv++;
    if(d != 1) a[pv].p = d,a[pv].k = 1,pv++;
}

void dfs(int pos,long long mul)
{
    if(pos == pv && sum_AB % mul == 0)
    {
        X = mul + B;
        Y = sum_AB / mul + A;
        if(X >= M && (ansX+ansY > X+Y || (ansX+ansY == X+Y && ansX > X)))
            ansX = X, ansY = Y;
        return;
    }
    long long accu = 1;
    for(int i=0; i<=a[pos].k; i++)
    {
        dfs(pos+1,mul*accu);
        accu *= a[pos].p;
    }
}

int main()
{
    //freopen("E:\\acm\\input.txt","r",stdin);
    get_prime();
    while(scanf("%lld %lld %lld",&A,&B,&M) == 3)
    {
        sum_AB = A*B;
        factor_analysis(A,B);
        ansX = 1e18+1, ansY = 1;
        dfs(0,1);

        if(ansX == 1e18+1 ) printf("No answer\n");
        else                printf("%lld %lld\n",ansX,ansY);
    }
}
View Code

 

posted @ 2014-03-18 19:23  等待最好的两个人  阅读(254)  评论(0编辑  收藏  举报