Hankson的趣味题

该博客主要介绍了如何使用数学知识和编程技巧解决实际问题。通过一道计算最大公约数(GCD)的问题,展示了如何将质因数分解与递归深度优先搜索(DFS)结合,找到所有满足条件的整数解。博客中首先进行了质因数分解的预处理,然后利用DFS遍历所有可能的组合,同时检查每个组合是否符合题目要求。最后,博主给出了完整的C++代码实现,并输出了符合条件的答案数量。
摘要由CSDN通过智能技术生成

题目:

题目链接:

题解:

#include  <bits/stdc++.h>
using namespace std;
const int N=45000;
int pri[N],primes[N];
int con,conf,cond;
typedef pair<int,int> pll;
pll f[N];
int yueshu[N];
void prime()
{
    for(int i=2;i<=N;i++)
    {
        if(!pri[i]) primes[++con]=i;
        for(int j=1;primes[j]<=N/i;j++)
        {
            pri[primes[j]*i]=1;
            if(i%primes[j]==0) break;
        }
    }
}
long long gcd(long long a,long long b)
{
    return b==0?a:gcd(b,a%b);
}
void dfs(int u,int p)
{
    if(u>conf)
    {
        yueshu[++cond]=p;
        return;
    }
    for(int i=0;i<=f[u].second;i++)
    {
        dfs(u+1,p);
        p*=f[u].first;
    }
}
int main()
{
    int n;
    cin>>n;
    prime();
    while(n--)
    {
        long long a,b,c,d;
        cin>>a>>b>>c>>d;
        long long m=d;
        conf=0;
        for(int i=1;primes[i]<=d/primes[i];i++)
        {
            int p=primes[i];
            int s=0;
            while(m%p==0)
            {
                s++;
                m/=p;
            }
            f[++conf]={p,s};
        }
        if(m>1) f[++conf]={m,1};
        cond=0;
        dfs(1,1);
        long long ans=0;
        for(int i=1;i<=cond;i++)
        {
            int x=yueshu[i];
            long long y=x*c;
            if(gcd(x,a)==b && y/gcd(x,c)==d)
            {
                ans++;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值