牛客网:S老师的公式 ← 取模运算

本文介绍了如何使用C++的辗转相除法求解最大公约数,讨论了取模运算的优化策略,以及在处理大规模数据时选择longlong型的重要性。给出了一个计算整数n*(n+1)/2与n的阶乘的最大公约数的示例代码。
摘要由CSDN通过智能技术生成

【题目来源】
https://ac.nowcoder.com/acm/contest/76652/A

【题目描述】
S 老师丢给你了一个简单的数学问题:
gcd(\sum_{i=1}^{n}i,\prod_{i=1}^{n}i)
请你求出答案。

【输入格式】
一行一个整数 n (1≤n≤10^6)。

【输出格式】
一行一个整数表示答案。

【说明】
例如,若n=3,则本题求解 gcd(1+2+3,1*2*3)=gcd(6,6)=6

【算法分析】

● 辗转相除法求最大公约数:https://blog.csdn.net/hnjzsyjyj/article/details/136276606

#include <bits/stdc++.h>
using namespace std;
 
int gcd(int a,int b) {
    if(b==0) return a;
    else return gcd(b,a%b);
}
 
int main() {
    int n;
    cin>>n;
    while(n--) {
        int a,b;
        cin>>a>>b;
        cout<<gcd(a,b)<<endl;
    }
 
    return 0;
}
 
 
/*
in:
2
3 6
4 6
out:
3
2
*/

● 取模运算规则:https://blog.csdn.net/hnjzsyjyj/article/details/120275467
因为本题数据规模高达10^6,所以对其求阶乘是无法想象的。需进行取模优化。
可以证明,
gcd(a,b)=gcd(a,b%a),所以就有了本例中的代码 for(int i=1; i<=n; i++) y=y*i%x;
● 若整数超过10位,就选择用 long long 型。所以,本题切记使用 long long 型。
https://blog.csdn.net/hnjzsyjyj/article/details/132240042

【算法代码】

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;

LL gcd(LL a,LL b) {
    if(b==0) return a;
    else return gcd(b,a%b);
}

LL n;
int main() {
    cin>>n;
    LL x=n*(n+1)/2;
    LL y=1;
    for(int i=1; i<=n; i++) y=y*i%x;
    cout<<gcd(x,y)<<endl; //__gcd(x,y)

    return 0;
}

/*
in:5
out:15
*/




【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/132240042
https://www.nowcoder.com/discuss/598465728497410048
https://blog.csdn.net/2303_76151267/article/details/136766539
https://blog.nowcoder.net/n/dce4118dc19b44b7972d37f376091c42





 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值