输入
第一行输入一个整数n
之后输入n行,每行输入一个数m,之后依次输入m个数
- 样例输入:
2
3 5 7 15
6 4 10296 936 1287 792 1
输出
- 输出每行m个数的最大公约数
- 样例输出:
105
10296
解题代码:
import java.util.Scanner;
public class p1019 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0;i<n;i++) {
int m = sc.nextInt();
int[] arr = new int[m];
for(int j = 0;j<m;j++) {
arr[j] = sc.nextInt();
}
int tmp = arr[0];
int a,b;
for(int k = 1;k<m;k++) {
a = tmp;
b = arr[k];
tmp = a*(b/gcd(a, b));//避免越界
}
System.out.println(tmp);
}
sc.close();
}
//辗转相处法,更相减损术的算法实在看不懂(而且计算次数还多,涉及到位运算就不想看了)
public static int gcd(int a, int b) {
int r = 0;
if(a%b == 0) return b;
if(a>b) {
while(b>0) {
r = a%b;
a = b;
b = r;
}
return a;
} else {
return gcd(b, a);
}
}
}
如果大家有兴趣的话可以去看这篇博客上面写了求两个数最大公约数的算法:
http://blog.csdn.net/a253664942/article/details/51051268