- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- Sum of square-sums of first n natural numbers
- Find the sum of first $n$ odd natural numbers.
- Find three consecutive natural numbers such that the sum of the first and second is 15 more than the third.
- PHP program to calculate the sum of square of first n natural numbers
- Difference between sum of the squares of and square of sum first n natural numbers.
- Sum of sum of first n natural numbers in C++
- Python Program for cube sum of first n natural numbers
- 8085 program to find the sum of first n natural numbers
- Python Program for Sum of squares of first n natural numbers
- Maximum sum of distinct numbers such that LCM of these numbers is N in C++
- Sum of square of first n odd numbers
- Program to find sum of first n natural numbers in C++
- Sum of first n natural numbers in C Program
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M in Python

Advertisements