给定一个整数N ,任务是找到可用于表示N的最大不同正整数个数。
例子:
Input: N = 5
Output: 2
5 can be represented as 1 + 4, 2 + 3, 3 + 2, 4 + 1 and 5.
So maximum integers that can be used in the representation are 2.
Input: N = 10
Output: 4
方法:我们总是可以贪婪地选择不同的整数,使其尽可能地小,以使可以使用的不同整数的数量最大化。如果我们使用的是前x个自然数,则将它们的和设为f(x)。
因此,我们需要找到一个最大值x,使得f(x)<= n。
1 + 2 + 3 + … n < = n
x*(x+1)/2 < = n
x^2+x-2n < = 0
We can solve the above equation by using quadratic formula X = (-1 + sqrt(1+8*n))/2.
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the required count
int count(int n)
{
return int((-1 + sqrt(1 + 8 * n)) / 2);
}
// Driver code
int main()
{
int n = 10;
cout << count(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the required count
static int count(int n)
{
return (int)(-1 + Math.sqrt(1 + 8 * n)) / 2;
}
// Driver code
public static void main (String[] args)
{
int n = 10;
System.out.println(count(n));
}
}
// This code is contributed by ihritik
Python3
# Python3 implementation of the approach
from math import sqrt
# Function to return the required count
def count(n) :
return (-1 + sqrt(1 + 8 * n)) // 2;
# Driver code
if __name__ == "__main__" :
n = 10;
print(count(n));
# This code is contributed by AnkitRai01
C#
// C# implementation of approach
using System;
class GFG
{
// Function to return the required count
public static int count(int n)
{
return (-1 + (int)Math.Sqrt(1 + 8 * n)) / 2;
}
// Driver Code
public static void Main()
{
int n = 10;
Console.Write(count(n));
}
}
// This code is contributed by Mohit Kumar
Javascript
输出:
4
时间复杂度: O(1)