笔试题:求整数序列中三个数的最大公约数:
程序员文章站
2024-03-14 19:37:22
...
题目:
有一组正整数序列a1,a2,…an,请计算出其中满足最大公约数为1的三个数ai,aj,ak的组合的数量,ai,aj,ak范围为1<=i<j<k<=N。
输入描述:
第一行输入包含一个整数N,表示序列的长度;
第二行包含N个空格分隔的整数,分别为a1,a2…an
输出描述:
输出为一行,内容满足条件的组合的数量;
示例:
输入:8
1 2 3 4 5 6 7 8
输出:52
思路:首先要会求两个数的最大公约数,之后稍微改变一下就可以啦。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Scanner sc2 = new Scanner(System.in);
String str=sc2.nextLine();
int[] array = new int[n];
String[] arr = str.split(" ");
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(arr[i]);
}
System.out.println(func(array));
}
private static int func(int[] array) {
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
for (int k = j + 1; k < array.length; k++) {
if (gcdfunc(array[i], gcdfunc(array[j], array[k]))==1) {
count++;
}
}
}
}
return count;
}
private static int gcdfunc(int a, int b) {
if (a <= 0 || b <= 0) {
return 0;
}
int R;
while ((R = a % b) > 0) {
a = b;
b = R;
}
return b;
}
}
上一篇: 简述python 的模块的分析
下一篇: 求约数个数的和
推荐阅读