In the problem you need to find G by the entered value n . GCD (i, j) is the gcd of numbers i and j .
The program works as it should, but for large n the execution time is colossal (for n = 30,000, for example, the program runs for about a minute).
Can you tell me how to optimize it?
Some questions:
1) Judging by the amounts, the numbers i and j are Fibonacci numbers, am I right? And if so, can this somehow help to facilitate the NOD search algorithm (the greatest common divisor of two Fibonacci numbers is equal to the Fibonacci number with the index equal to the largest common divider of the indices)? To search for ged, I used the Euclidean algorithm.
2) Is it possible to somehow speed up the calculation of the sum, that is, to avoid the use of two nested cycles and a huge number of iterations arising from them?
public class Main { public static void main(String[] args){ Scanner reader = new Scanner(System.in); int n; List<Integer> a = new ArrayList<>(); for( ; ; ) { n = reader.nextInt(); if(n>1 && n<4000001) a.add(n); else if(n==0) break; } int i, j; for (int k=0; k<a.size(); k++) { n=a.get(k); long G = 0; for( i = 1; i < n; i++) { for( j = i + 1;j <= n; j++) { G += GCD(i,j); } } System.out.println(G); } } static int GCD (int i, int j) { while (j !=0) { int tmp = i%j; i = j; j = tmp; } return i; } } 