[关闭]
@chawuciren 2019-09-15T04:52:30.000000Z 字数 679 阅读 545

CINTA作业3-编程题(GCD、EGCD)

CINTA


1、实现GCD算法的迭代版本;

  1. /*
  2. * Input: two integers (a and b)
  3. * Output: the greatest common divisor of a and b
  4. * Method: iteration
  5. */
  6. int gcd(int a, int b){
  7. int temp;
  8. do{
  9. temp = a%b;
  10. a = b;
  11. b = temp;
  12. }while(b);
  13. return a;
  14. }

2、实现EGCD的C语言版本;

  1. /*
  2. * Input: integers a and b(a>b)
  3. * Output: d(the greatest common divisor of a and b),s and *r(Bézout's coefficient)
  4. * Method: iteration
  5. */
  6. void egcd(int a, int b, int* s, int * r,int*d){
  7. int r0=1,s1 = 1;
  8. int r1=0,s0=0,q = 0,temp=0;
  9. while (b){
  10. q = a / b; //Seeking quotient
  11. a = a%b;
  12. swap(&a,&b);//Gcd algorithm on the right side of the equation
  13. r0 = r0-(q*r1);//Gcd algorithm on the left side of the equation
  14. swap(&r0,&r1);
  15. s0 = s0 - (q*s1);
  16. swap(&s0,&s1);
  17. }
  18. *s = s0;
  19. *r = r0;
  20. *d = a;
  21. }
  22. void swap(int*a,int *b){//Exchange the values of a and b
  23. int temp=*a;
  24. *a=*b;
  25. *b=temp;
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注