Funny Divisors in java

Funny Divisors in java

Ninja is bored with his previous game of numbers, so now he is playing with divisors. He is given ‘N’ numbers, and his task is to return the sum of all numbers which is divisible by 2 or 3.

Let the number given to him be – 1, 2, 3, 5, 6. As 2, 3, and 6 is divisible by either 2 or 3 we return 2 + 3 + 6 = 11.

##Input Format

The first line of input contains a single integer ‘N’, denoting the number of elements given to Ninja. The next line contains the ‘N’ space separated by integers given to Ninja.

##Output Format

Only line of input contains an integer denoting the sum of numbers divisible by 2 or 3.

Example 1

Input

3
1 2 3

Output

5

Explanation

Here, 1 is neither divisible by 2 or 3. 2 is divisible by 2, and 3 is divisible by 3. So here we return the sum of 2 + 3 which is equal to 5.

Example 2

Input

4
5 6 9 8

Output

23

Explanation

Here, 5 is divisible by neither 2 nor 3.6 is divisible by 2, 9 is divisible by 3, and 8 is divisible by 2. So here we return 6 + 9 + 8 = 23.

Constraints

1 <= N <= 10^3 0 <= input[i] <= 10^3

Solution Funny Divisors in java:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();

      int arr[]= new int[n];
      for(int i=0;i<n;i++)
        {
          arr[i]=sc.nextInt();
        }

      int result[] = new int [n];
      int count=0;
      for(int i=0;i<n;i++)
        {
          if(arr[i]%2==0 || arr[i]%3==0)
          {
             result[count]=arr[i];
             count++;
          }
        }

      int sum=0;
      for(int i=0;i<n;i++)
        {
          sum=sum+result[i];
        }

      System.out.print(sum);
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *