Funny Divisors

Easy
0/40
Average time to solve is 15m
36 upvotes
Asked in company
Bank Of America

Problem statement

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.

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains ‘T’, denoting the number of test cases.

Each test case contains a single integer ‘N’, denoting the number of elements given to Ninja.

The next line contains the ‘N’ elements given to Ninja.
Output Format:
For each test case, return an integer denoting the sum of numbers divisible by 2 or 3.
Note:
You are not required to print the expected output. It has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10
1 <= N <= 10^3
0 <= input[i] <= 10^3

Where ‘T’ denotes the number of test cases and ‘N’ is the elements given to Ninja and input[i] denotes theith input.

Time Limit: 1 sec  
Sample Input 1 :
2
3
1 2 3
4
5 6 9 8
Sample Output 1 :
5
23  
Explanation for Sample Input 1 :
In the first test case, 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.

In the second test case, 5 is divisible by neither 5 nor 6.6 is divisible by 2, 9 is divisible by 3, and 8 is divisible by 2. So here we return 6 + 9 + 8 = 23. 
Sample Input 2 :
2
7
7 5 11 3 5 2 9
2
3 4
Sample Output 2 :
14
7
Hint

Can you check whether a number is divisible by 2 or 3 ? 

Approaches (1)
Brute force

The key here is to traverse all the elements in the given array and check whether it is divisible by 2 or 3, and simultaneously add the value to the sum.

The steps are as follows:

  • We will initialize a variable ‘sum’ to 0, which will store the sum of numbers divisible by 2 or 3.
  • We will iterate from i = 0 to N - 1:
  • If the element at ith index is divisible by 2 or 3 then add it to ‘sum’.
  • We will return the sum as the final answer.
Time Complexity

O(N), where N is the number of lines.
 

 As we are checking for all the elements in the given array

 Hence, the overall complexity is O(N).

Space Complexity

O(1)

 

As we are not using any extra space. Hence, the overall space complexity is O(1).

Code Solution
(100% EXP penalty)
Funny Divisors
Full screen
Console