现在的位置: 首页 > 综合 > 正文

求最大公约数的Stein算法以及高精度实现 求最大公约数的Stein算法以及高精度实现

2017年11月04日 ⁄ 综合 ⁄ 共 984字 ⁄ 字号 评论关闭
 

求最大公约数的Stein算法以及高精度实现

分类: 数论 59人阅读 评论(0) 收藏 举报

首先来介绍一下什么是Stein算法

  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. int abs(int x)  
  6. {  
  7.     return x>0? x:-x;  
  8. }  
  9.   
  10. int gcd(int a,int b)  
  11. {  
  12.     if(a==0) return b;  
  13.     if(b==0) return a;  
  14.     if(a%2==0&&b%2==0)   return 2*gcd(a/2,b/2);  
  15.     else if(a%2==0)      return gcd(a/2,b);  
  16.     else if(b%2==0)      return gcd(a,b/2);  
  17.     else                 return gcd(abs(a-b),min(a,b));  
  18. }  
  19.   
  20. int main()  
  21. {  
  22.     int a,b;  
  23.     while(cin>>a>>b)  
  24.     {  
  25.         cout<<gcd(a,b)<<endl;  
  26.     }  
  27.     return 0;  
  28. }  


 题目:高精度GCD

 

Java代码:

  1. import java.util.*;  
  2. import java.math.BigInteger;  
  3.   
  4. public class Main  
  5. {  
  6.       public static void main(String[] args)  
  7.       {  
  8.             Scanner cin = new Scanner(System.in) ;  
  9.             BigInteger a =cin.nextBigInteger();  
  10.             BigInteger b =cin.nextBigInteger();  
  11.             BigInteger ans=a.gcd(b);  
  12.             System.out.println(ans);  
  13.       }  

抱歉!评论已关闭.