Python/C/C++/JAVA

Basic Practice Programs with Code and Concept

By D.S

Greatest Common Divisor(GCD)

(a.) C Code


    #include <stdio.h>

    int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }

    int main() {
        int a, b;
        printf("Enter first number: ");
        scanf("%d", &a);
        printf("Enter second number: ");
        scanf("%d", &b);
        printf("GCD of %d and %d is: %d
", a, b, gcd(a, b));
        return 0;
    }
    
Output:-
Enter first number: 24
Enter second number: 36
GCD of 24 and 36 is: 12

(b.) C++ Code

#include <iostream>

    using namespace std;

    int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }

    int main() {
        int a, b;
        cout << "Enter first number: ";
        cin >> a;
        cout << "Enter second number: ";
        cin >> b;
        cout << "GCD of " << a << " and " << b << " is: " << gcd(a, b) << endl;
        return 0;
    }
Output:-
Enter first number: 24
Enter second number: 36
GCD of 24 and 36 is: 12

(c.) Python Code

def gcd(a, b):
        while b:
            a, b = b, a % b
        return a

    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))
    print("GCD of", a, "and", b, "is:", gcd(a, b))
Output:-
Enter first number: 24
Enter second number: 36
GCD of 24 and 36 is: 12

(d.) Java Code

import java.util.Scanner;

    public class GCD {
        public static int gcd(int a, int b) {
            if (b == 0)
                return a;
            return gcd(b, a % b);
        }

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter first number: ");
            int a = scanner.nextInt();
            System.out.print("Enter second number: ");
            int b = scanner.nextInt();
            System.out.println("GCD of " + a + " and " + b + " is: " + gcd(a, b));
        }
    }
Output:-
Enter first number: 24
Enter second number: 36
GCD of 24 and 36 is: 12