Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C ใช้งานอัลกอริทึมยุคลิด (Euclid's Algorithm) หา GCD และ LCM

โจทย์

นำอัลกอริทึมยุคลิดมาหา ตัวหารร่วมมาก (GCD) และ ตัวคูณร่วมน้อย (LCM) ของจำนวนเต็มสองจำนวน แล้วแสดงผลพร้อมตัวเลขที่ป้อนเข้า

วิธีแก้

ตรรกะหา GCD และ LCM:

if(firstno*secondno!=0){    gcd=gcd_rec(firstno,secondno);    printf("\nThe GCD of %d and %d is %d\n",firstno,secondno,gcd);    printf("\nThe LCM of %d and %d is %d\n",firstno,secondno,(firstno*secondno)/gcd); }

ฟังก์ชันเรียกซ้ำ (recursive function):

int gcd_rec(int x, int y){    if (y == 0)       return x;    return gcd_rec(y, x % y); }

โปรแกรม

โปรแกรม C ใช้งานอัลกอริทึมยุคลิดหา GCD และ LCM:

#include<stdio.h> int gcd_rec(int,int); void main(){    int firstno,secondno,gcd;    printf("Enter the two no.s to find GCD and LCM:");    scanf("%d%d",&firstno,&secondno);    if(firstno*secondno!=0){       gcd=gcd_rec(firstno,secondno);       printf("\nThe GCD of %d and %d is %d\n",firstno,secondno,gcd);       printf("\nThe LCM of %d and %d is %d\n",firstno,secondno,(firstno*secondno)/gcd);    }    else       printf("One of the entered no. is zero:Quitting\n");    }    /*Function for Euclid's Procedure*/    int gcd_rec(int x, int y){    if (y == 0)       return x;    return gcd_rec(y, x % y); }

ผลลัพธ์

Enter the two no.s to find GCD and LCM:4 8 The GCD of 4 and 8 is 4 The LCM of 4 and 8 is 8