Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For Problem 1, name your source code gcd.ext, where ext denotes one of { java, c

ID: 3859921 • Letter: F

Question

For Problem 1, name your source code gcd.ext, where ext denotes one of { java, cpp, py, cs } that indicates java/c++/python/mono language. You need to use just one source file per problem.

Problem Statement 1: Computing GCD Read in a sequence of 32-bit signed integers (several per line separated by spaces) until a single line containing zero (0). There will be at most 1000 integers per line. For each line except for the last one, compute the greatest common divisor (gcd) of that set of integers. Then output on a line the statement "The ged of the integers is x." where z is the desired ged. Note, for this problem, all answers should be non-negative. The input should be taken from keyboard/stdin/System.in Sample Input: 8 15 0 -5 6 20 25 5 30 28 21952 49 294 3822 0 The precisely formated output should be sent to console/stdout/System.out Sample Output: The ged of the integers is 2 The gcd of the integers is 5 The ged of the integers is 1. The ged of the integers is 7

Explanation / Answer

Below is your code: -

gcd.java

import java.util.ArrayList;

import java.util.Scanner;

//Java program to find GCD of two or

//more numbers

public class gcd {

// Function to return gcd of a and b

static int gcd1(int a, int b) {

if (a == 0)

return b;

return gcd1(b % a, a);

}

// Function to find gcd of array of

// numbers

static int findGCD(int arr[], int n) {

int result = arr[0];

for (int i = 1; i < n; i++)

result = gcd1(arr[i], result);

return result;

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

ArrayList<Integer> gcdArr = new ArrayList<>();

System.out.println("Enter numbers : ");

while (sc.hasNextLine()) {

String line = sc.nextLine();

if (!line.equals("0")) {

String[] ints = line.split(" ");

int count = 0;

int[] nums = new int[ints.length];

for (int i = 0; i < ints.length; i++) {

if (ints[i].length() > 0) {

nums[count++] = Integer.parseInt(ints[i]);

}

}

int gcd = findGCD(nums, count);

gcdArr.add(Math.abs(gcd));

} else {

break;

}

}

for (int i = 0; i < gcdArr.size(); i++) {

System.out.println("The gcd of the integers is " + gcdArr.get(i));

}

}

}

Sample Output: -

Enter numbers :
2 4 8
15 0 -5
6 20 25 5 30
28 21952 49 294 3822
0
The gcd of the integers is 2
The gcd of the integers is 5
The gcd of the integers is 1
The gcd of the integers is 7

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote