gcd 模板 以及最小公倍数

来源:互联网 发布:配电网自动化数据 编辑:程序博客网 时间:2024/06/01 13:14
下面代码是求最大公约数
//递归版int gcd(int a,int b){    return b?gcd(b,a%b):a;}//非递归版int gcd(int a,int b){    while(b)    {        int t=a%b;        a=b;        b=t;    }    return a;}


最小公倍数等于:原来两个数a,b的乘积除以最大公约数





交换两个数的值:
if(a<b)            a=a^b,b=a^b,a=a^b;

gcd
#include<stdio.h>int gcd(int a,int b){    return b?gcd(b,a%b):a;}int main(){    int a,b;    while(scanf("%d%d",&a,&b)!=EOF)    {        if(a<b)            a=a^b,b=a^b,a=a^b;        printf("%d\n",gcd(a,b));    }    return 0;}


最大公约数
#include<stdio.h>#define LL long longLL gcd(LL a,LL b){    return b?gcd(b,a%b):a;}int main(){    LL a,b;    while(scanf("%lld%lld",&a,&b)!=EOF)    {        if(a<b)            a=a^b,b=a^b,a=a^b;        printf("%lld\n",a*b/gcd(a,b));    }    return 0;}



0 0
原创粉丝点击