跳到正文

个人记录

long long 与 int 的运算速度比较

Midvoy_尺约 3 分钟
原文
文章信息与版本

文章信息

发布
2019年7月24日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 3 分钟

版本

  1. v1当前

背景:

在打数论(弱科)模板题【模板】乘法逆元时,si都过不去(没有用递推的后果):

C
#include<cstdio>
#define ll long long
using namespace std;
ll n,p,x,y;
ll ans;
ll exgcd(ll a,ll b) {
    if(!b){
        x=1;
        y=0;
        return a;
      }
    ll d=exgcd(b,a % b);
    ll tmp=x;
    x=y;
    y=tmp-a/b*y;
}
int main(){
    scanf("%lld%lld",&n,&p);
    for(int i=1;i<=n;++i){
        exgcd(i,p);
        ans=(x%p+p)%p;
        printf("%lld\n",ans);
    }
    return 0;
}
/**************************************************************
    Problem: 2074
    User: Midvoy_尺
    Language: C++
    Result: 时间超限
****************************************************************/

直到找到一位大佬灵机一动:

C
#include<cstdio>
#define ll int
using namespace std;
ll n,p,x,y;
ll ans;
ll exgcd(ll a,ll b) {
    if(!b){
        x=1;
        y=0;
        return a;
      }
    ll d=exgcd(b,a % b);
    ll tmp=x;
    x=y;
    y=tmp-a/b*y;
}
int main(){
    scanf("%d%d",&n,&p);
    for(int i=1;i<=n;++i){
        exgcd(i,p);
        ans=(x%p+p)%p;
        printf("%d\n",ans);
    }
    return 0;
}
/**************************************************************
    Problem: 2074
    User: Midvoy_尺
    Language: C++
    Result: 正确
    Time:796 ms
    Memory:1092 kb
****************************************************************/

我…无语了,就long long改成了int,%lld改为%d就过了。

结论:

long long mod(%) 的速度 比int慢一半

所以能用int就少用longlong

考试时万万不得作死~~

原文