Pages

Sunday 2 December 2012

UVA - 11424 - GCD - Extreme (I) (Java solution)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb = new StringBuffer("");
        long[]arr=phi(200001);
        while (true) {
           int x=Integer.parseInt(br.readLine().trim());
           if(x==0)
               break;
           sb.append(arr[x]).append("\n");
        }
        System.out.print(sb);
    }
   
    static long[] phi(int n){
        long[] arr = new long[n+1];
        long[] ans = new long[n];
        arr[1] = 1;
        for (int i = 2; i < n+1; i++) {
            if (arr[i] == 0) {
                arr[i] = i - 1;
                for (int j =2*i; j < n+1; j += i) {
                    if (arr[j] == 0) {
                        arr[j] = j;
                    }
                    arr[j] = arr[j]/i * (i - 1);
                }
            }
        }
        for (int i = 1; i < n; i++) {
            for (int j = 2*i; j < n; j += i) {
                ans[j] += (i * arr[j / i]);
            }
        }
        for (int i = 2; i < n; i++) {
            ans[i] += ans[i - 1];
        }
        return ans;
    }
}

No comments:

Post a Comment