- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Following is the Java program for GCD of more than two numbers −

public class Demo{ static int gcd_of_nums(int val_1, int val_2){ if (val_1 == 0) return val_2; return gcd_of_nums(val_2 % val_1, val_1); } static int find_gcd(int arr[], int no){ int result = arr[0]; for (int i = 1; i < no; i++){ result = gcd_of_nums(arr[i], result); if(result == 1){ return 1; } } return result; } public static void main(String[] args){ int my_arr[] = { 7, 49, 177, 105, 119, 42}; int no = my_arr.length; System.out.println("The GCD of the elements in the array is "); System.out.println(find_gcd(my_arr, no)); } }

The GCD of the elements in the array is 1

A class named Demo contains a main function that takes in two values. If the first value is 0, the second value is returned as output. Otherwise, a recursive function is written that computes the greatest common divisor of the two elements.

Next, another static function is defined that takes an array and another integer value as parameter. The first element of the array is assigned to a variable named ‘result’ and a ‘for’ loop iterates over elements from 1 to the integer value that was passed as a parameter to the function. The greatest common divisor function is called on this array elements and a result. This output is assigned to ‘result’ variable itself. If the value of ‘result’ is 1, then the output is 1, otherwise the value of ‘result’ is returned.

In the main function, an array integer is defined and the length of the array is assigned to a specific value. The greatest common divisor function is called on the array elements and length. Relevant data is displayed on the console.

- Related Questions & Answers
- C++ Program for GCD of more than two (or array) numbers?
- Python Program for GCD of more than two (or array) numbers
- C++ Program for GCD 0.of more than two (or array) numbers?
- GCD of more than two (or array) numbers in Python Program
- Finding LCM of more than two (or array) numbers without using GCD in C++
- Java program to find the GCD or HCF of two numbers
- Program to find GCD or HCF of two numbers in C++
- Find GCD of two numbers
- GCD and LCM of two numbers in Java
- GCD of an array of numbers in java
- Java Program for Common Divisors of Two Numbers
- Program to find GCD or HCF of two numbers using Middle School Procedure in C++
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm
- C# program to find Union of two or more Dictionaries
- C# program to find Union of two or more Lists

Advertisements