Write a C program to calculate the GCD of two numbers using the Euclidean algorithm.

Function Main
    Declare Integer A
    Declare Integer B
    Declare Integer res
    
    Output "Insert 2 numbers to calculate GCD"
    Output "First number: "
    Input A
    Output "Second number"
    Input B
    Assign res = GCD(a,b)
    Output res
End

Function GCD (Integer a, Integer b)
    Declare Integer res
    
    If a = 0
        Assign res = b
    Else
        Assign res = GCD(b MOD a, a)
    End
Return Integer res

#include <stdio.h>

int GCD(int a, int b);

int main() {
    int a;
    int b;
    int res;
    
    printf("Insert 2 numbers to calculate GCD:\n");
    printf("First number: \n");
    scanf("%d", &a);
    printf("Second number:\n");
    scanf("%d", &b);
    res = GCD(a, b);
    printf("%d\n", res);
    return 0;
}

int GCD(int a, int b) {
    int res;
    
    if (a == 0) {
        res = b;
    } else {
        res = GCD(b % a, a);
    }
    
    return res;
}

Insert 2 numbers to calculate GCD:
First number: 
5
Second number:
15
5

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.