Maximize X such that sum of numbers in range [ 1 , X ] is at most K | Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores the result ; Iterate until low is less than or equal to high ; Stores the sum of first mid natural numbers ; If sum is less than or equal to K ; Update res and low ; Otherwise , ; Update ; Return res ; Driver Code ; Input ; Function call
def Count ( N , K ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE low = 1 NEW_LINE high = N NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE sum = ( mid * mid + mid ) // 2 NEW_LINE if ( sum <= K ) : NEW_LINE INDENT res = max ( res , mid ) NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE K = 14 NEW_LINE print ( Count ( N , K ) ) NEW_LINE DEDENT