Subtraction Game 1 Codechef Solution

Hello Programmers In this post, you will know how to solve the Subtraction Game 1 Codechef Solution. Problem Code: AMSGAME1

Subtraction Game 1 Codechef Solution
Subtraction Game 1 Codechef Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Codechef by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Problem

Chef is playing a game on a sequence of N positive integers, say A1, A2, … AN. The game is played as follows.

  • If all the numbers are equal, the game ends.
  • Otherwise
    • Select two numbers which are unequal
    • Subtract the smaller number from the larger number
    • Replace the larger number with the result from above (see the explanation section for clarity)

Chef has already figured out that the game always terminates. He also knows, for a given sequence of integers, the game will always terminate on the same value, no matter how the game is played. Chef wants you to simulate the game for him and tell him on which value will the game terminate for a given sequence of integers.

Input

The first line of the input contains an integer T, the number of test cases. Then follow the description of T test cases. The first line of each test case contains a single integer N, the length of the sequence. The second line contains N positive integers, each separated by a single space.

Output

For each test case, output a single integer – the value of all the numbers when they are equal (and the game terminates), on a line by itself.

Constraints

1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ Ai ≤ 109

Sample Input 1 

```
3
2
10 12
2
5 9
3
6 10 15
```

Sample Output 1 

```
2
1
1
```

Subtraction Game 1 CodeChef Solution in JAVA

import java.util.Arrays;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for (int tc = 0; tc < T; tc++) {
			int N = sc.nextInt();
			int[] A = new int[N];
			for (int i = 0; i < A.length; i++) {
				A[i] = sc.nextInt();
			}
			System.out.println(solve(A));
		}
		sc.close();
	}
	static int solve(int[] A) {
		return Arrays.stream(A).reduce(Main::gcd).getAsInt();
	}
	static int gcd(int a, int b) {
		return (b == 0) ? a : gcd(b, a % b);
	}
}

Disclaimer: The above Problem (Subtraction Game 1 ) is generated by CodeChef but the solution is provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Next: Bhallaladeva Codechef Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad