Sum or Product

Easy
0/40
Average time to solve is 15m
profile
Contributed by
1532 upvotes
Asked in companies
Tata Consultancy Services (TCS)OkcreditNosh technologies

Problem statement

You are given a number ‘N’ and a query ‘Q.’ If ‘Q’ is 1, then you have to return the sum of all integers from 1 to ‘N,’ else if ‘Q’ is equal to 2 then you have to return the product of all integers from 1 to ‘N.’ Since the product can be very large, return it modulo 10 ^ 9 + 7.

For example

Given ‘N’ = 4, ‘Q’ = 1. 
Then the answer is 10 because the sum of all integers between 1 and 4 are 1, 2, 3, and 4. Hence 1 + 2 + 3 + 4 is equal to 10.
Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

Next, ‘T’ lines contain two space-separated integers ‘N’, where ‘N’ is the number given and ‘Q’, denoting the type of query.
Output Format :
For each test case, You are supposed to return an integer denoting the sum or product of ‘N’ numbers.
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^4
1 <= ‘Q’ <= 2

Time Limit: 1 sec.

Sample Input 1 :

2
4 1 
4 2

Sample Output 1 :

10
24 

Explanation of the Sample Input 1:

In the first test case, the answer is 10 because all integers between 1 and 4 are 1, 2, 3, and 4. Hence 1 + 2 + 3 + 4 is equal to 10.


In the second test case, the answer is 25 because all integers between 1 and 4 are 1, 2, 3, and 4. Hence 1 * 2 * 3 * 4 is equal to 24.

Sample Input 2 :

2
5 1
5 2 

Sample Output 2 :

15
120
Hint

Can you figure out how to find the sum and product of numbers from 1 to N?

Approaches (1)
Brute force

The idea is to loop for the given ‘N’ according to the query ‘Q.’ It can be easily seen that sum of the first ‘N’ integers is represented by (‘N’ * ‘N + 1’) / 2. But for the product, we will have to loop from 1 to N.

 

The steps are as follows:

  • Maintain a variable ‘answer’ that stores the final result.
  • If ‘Q’ is 1:
    • ‘answer’ = (‘N’ * ‘N + 1’) / 2
  • Else:
    • Loop from 1 to ‘N’ using ‘i’.
    • For each iteration, multiply ‘i’ to ‘answer.’
  • Return ‘answer’ as the final answer.
Time Complexity

O(N), where ‘N’ is the number given.
 

Since in the worst case, we are looping from 1 to ‘N,’ Hence the overall complexity will be O(N).

Space Complexity

O(1).

 

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

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Sum or Product
Full screen
Console