The Great Kian | Competitive Programming Questions with Answers in Java

Competitive Programming Questions with Answers in Java

The Great Kian

Problem

The great Kian is looking for a smart prime minister. He's looking for a guy who can solve the OLP (Old Legendary Problem). OLP is an old problem (obviously) that no one was able to solve it yet (like P=NP).

But still, you want to be the prime minister really bad. So here's the problem:

Given the sequence a1, a2, ..., an find the three values a1 + a4 + a7 + ..., a2 + a5 + a8 + ... and a3 + a6 + a9 + ... (these summations go on while the indexes are valid).



Input
The first line of input contains a single integer n (1 ≤ n ≤ 105).
The second line contains n integers a1, a2, ..., an separated by space (1 ≤ ai ≤ 109).

Output
Print three values in one line (the answers).

Sample Input
5
1 2 3 4 5

Sample Output

5 7 3

Solution

import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {
        int n, i;
        long n1=0, n2=0, n3=0;
        Scanner s = new Scanner(System.in);
        n = s.nextInt();
        int[] a = new int[n];
        for(i=0; i<n; i++)
        {
            a[i] = s.nextInt();
        }
        for(i=0; i<n; i = i + 3)
        {
            n1 = n1 + a[i];
            if(i+1 < n)
                n2 = n2 + a[i + 1];
            if(i+2 < n)
                n3 = n3 + a[i + 2];
        }
        System.out.println(n1 + " " + n2 + " " + n3);
    }
}

Comments