- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find maximum N such that the sum of square of first N natural numbers is not more than X in Python
Suppose we have a given integer X, we have to find the maximum value N so that the sum of first N natural numbers should not exceed the value X.
So, if the input is like X = 7, then the output will be 2 as 2 is the maximum possible value of N, for N = 3, the sum of the series will exceed X = 7 So, 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14.
To solve this, we will follow these steps −
Define a function sum_of_squares() . This will take N
res :=(N *(N + 1) *(2 * N + 1)) / 6
return res
From the main method, do the following −
low := 1
high := 100000
N := 0
while low −= high, do
mid :=(high + low) / 2
if sum_of_squares(mid) −= X, then
N := mid
low := mid + 1
otherwise,
high := mid - 1
return N
Example
Let us see the following implementation to get better understanding −
def sum_of_squares(N): res = (N * (N + 1) * (2 * N + 1)) // 6 return res def get_max(X): low, high = 1, 100000 N = 0 while low <= high: mid = (high + low) // 2 if sum_of_squares(mid) <= X: N = mid low = mid + 1 else: high = mid - 1 return N X = 7 print(get_max(X))
Input
7
Output
2