GCD

題目:最大公因數(輾轉相除法)
程式碼:

#include <stdio.h>
#include <stdlib.h> 

int main(void) {
 int a,b;//輸入數字a,b
 scanf("%d %d",&a,&b);//鍵盤輸入
 int t = 0;
 int c = 0;
 if(a>b){
  while(b!=0){
   t = a%b;
   a = b;
   b = t;
   c++;
  } 
  printf("GCD=%d,共%d次",a,c);
 }else{
  while(a!=0){
   t = b%a;
   b = a;
   a = t;
   c++;
   
  }
  printf("GCD=%d,共%d次",b,c);
 }
 
}

留言

熱門文章