Write a program to calculate the GCD of given numbers using recursion
Example:
Input: a = 10, b= 24 Output: GCD of numbers is 2
Approach
C
#include <stdio.h>int gcdRec(int a, int b){if (b == 0)return a;return gcdRec(b, a % b);}int main(){int a, b;printf("Enter two numbers: ");scanf("%d%d", &a, &b);int gcd = gcdRec(a, b);printf("GCD of numbers is %d ", gcd);return 0;}
Java
import java.util.Scanner;public class GCDGivenNumber {public static void main(String[] args) {System.out.println("Enter the First number");Scanner sc = new Scanner(System.in);int a = sc.nextInt();System.out.println("Enter the Second number");int b = sc.nextInt();int gcd = gcdRec(a, b);System.out.println("GCD of numbers is " + gcd);sc.close();}private static int gcdRec(int a, int b) {if (b == 0)return a;return gcdRec(b, a % b);}}
Related posts
- Write a program to calculate the GCD of given two numbers
- Write a program to find GCD using the Extended Euclidean algorithm
No comments:
Post a Comment