HackerRank Solution: Summing the N series [2 Methods]


Hacker Rank Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Question: Summing the N series [Python Fundamentals]

There is a sequence whose term nth is:

summing-n-series

Evaluate the series:

series

Find Sn mod (10^9 + 7)

Example

n = 3

The series is 1^2 - 0^2 + 2^2 -1^2 +3^2 - 2^2 = 1 + 3 + 5+ = 9

Function Description

Complete the summingSeries function in the editor below.

summingSeries has the following parameter(s):

  • int n: the inclusive limit of the range to sum

Return

int: the sum of the sequence, modulo (10^9 + 7)

Input format

The first line of input contains t, the number of test cases.
Each test case consists of one line containing a single integer n.

Constraints

  • 1<=t<=10
  • 1<=n<=10^16

Sample Input 0

2
2
1

Sample Output 0

4
1

Explanation 0

Case 1: We have 4 = 1+ 3
Case 2: We have 1 = 1

 

Possible solutions

Now let us jump into the possible solutions. The following code is already given in the hacker rank:

import math
import os
import random
import re
import sys

#
# Complete the 'summingSeries' function below.
#
# The function is expected to return an INTEGER.
# The function accepts LONG_INTEGER n as parameter.
#

def summingSeries(n):
    # Write your code here

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

    for t_itr in range(t):
        n = int(input().strip())

        result = summingSeries(n)

        fptr.write(str(result) + '\n')

    fptr.close()

We just need to complete the summingSeries() function:

 

Solution-1:  Using modulo

Let us first use the modulo to solve the given problem

import math
import os
import random
import re
import sys


def summingSeries(n):
    return (n*n) % 1000000007

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

    for t_itr in range(t):
        n = int(input().strip())

        result = summingSeries(n)

        fptr.write(str(result) + '\n')

    fptr.close()

The summingSeries() function takes in a single parameter "n". Inside the function, it calculates the square of "n" and then calculates the remainder when that value is divided by 1000000007. This remainder is then returned as the output of the function. This function can be used to calculate the sum of the series n^2 for some range of numbers.

It's using modulo operator(%) to get the remainder when nn is divided by 1000000007. This is useful when the number nn is very large, and we want to reduce the size of the result. This way we can handle large numbers without the need for BigInteger data types.

 

Solution-2: Using pow() method

In Python, we can use the pow() method to find the power of the number. Let us now use the pow() method to solve the given problem.

import math
import os
import random
import re
import sys


def summingSeries(n):
  return pow(n, 2) % (10**9 + 7)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

    for t_itr in range(t):
        n = int(input().strip())

        result = summingSeries(n)

        fptr.write(str(result) + '\n')

    fptr.close()

This code is similar to the previous one, but it uses the "pow()" function instead of the multiplication operator (n*n) to calculate the square of "n". The "pow()" function takes two arguments: the base (in this case, "n") and the exponent (in this case, 2). It raises the base to the power of the exponent and returns the result. The rest of the code is the same: it takes the result of pow(n, 2) and then calculates the remainder when that value is divided by 1000000007. The only difference is that in the previous code it uses (n*n) to calculate the square of n, while in this code it uses pow(n,2) function which already calculates the square of the base. The overall effect is the same, both the codes are calculating the remainder when n^2 is divided by (10^9+7) but the only difference is the method used to calculate the square of n.

 

Summary

In this short article, we discussed how we can solve the summing the N series problem from hacker rank. We solved the problem using two different methods and explained both methods.

 

Further reading

Question on Hacker Rank: Summing the N series [Python Fundamentals]

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment