java 数组中对数的最大GCD

ezykj2lf  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(110)

我想在数组中找到对的最大GCD示例:2,4,7,9,14,15输出:7

  1. import java.util.Scanner;
  2. public class Solution {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. int n = sc.nextInt();
  6. int[] nums = new int[n];
  7. for (int i = 0; i < n; i++) {
  8. nums[i] = sc.nextInt();
  9. }
  10. int result = findMaxGCD(nums);
  11. System.out.println(result);
  12. }
  13. public static int findMaxGCD(int[] arr) {
  14. int maxGCD = 0;
  15. int n = arr.length;
  16. for (int i = 0; i < n - 1; i++) {
  17. for (int j = i + 1; j < n; j++) {
  18. int gcd = gcd(arr[i], arr[j]);
  19. if (gcd > maxGCD) {
  20. maxGCD = gcd;
  21. }
  22. }
  23. }
  24. return maxGCD;
  25. }
  26. public static int gcd(int a, int b) {
  27. if (b == 0)
  28. return a;
  29. return gcd(b, a % b);
  30. }
  31. }

我测试我的解决方案,但它有一个运行时的问题,它是超时。你能帮我保存更多的时间吗?
最好的解决方案。它有一个运行时的问题,它是超时。你能帮我保存更多的时间。

hpcdzsge

hpcdzsge1#

首先,你打开一个scanner对象,读取一个数字,然后打印结果,但是你必须在最后关闭scanner对象。
在读取输入后添加sc.close()

相关问题