给定一个整数N ,任务是找到前N个自然数的方差。
Variance is used to determine how far the data is spread from their average value. It is generally represented by symbol σ2 and the equation for finding the variance is generally given by the following equation:
∑Ni = 1 (xi– mean(x))2 / N
where N is the total number of data
例子:
Input: 5
Output: 2
Explanation:
Mean of the first 5 numbers = (1 + 2 + 3 + 4 + 5) / 5 = 3
Therefore, Variance = ((1 – 3)2 + (2 – 3)2 + (3 – 3)2+(4 – 3)2+(5 – 3)2) / 5 = (4 + 1 + 0 + 1 + 4) / 5 = 10 / 5.
Input: 4
Output: 1.25
Explanation:
Mean of first 4 numbers = (1 + 2 + 3 + 4) / 4 = 2.5
Therefore, Variance = ((1 – 2.5)2 + (2 – 2.5)2 + (3 – 2.5)2 + (4 – 2.5)2) / 4 = (2.25 + 0.25 + 0.25 + 2.25) / 4 = 5 / 4.
天真的方法:解决此问题的简单方法是,首先计算前N个自然数的均值,然后遍历范围[1,N]并计算方差。
时间复杂度: O(N)
辅助空间: O(1)
有效的解决方案:将上述溶液可以通过简化均值和方差的上述公式和使用所述第一N的自然数的总和的特性和所述第一n个自然数的平方和进行优化,如下所示。
。
因此,计算(N 2 – 1)/ 12并将其打印为所需结果。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to calculate Varaince
// of first N natural numbers
long double find_Variance(int n)
{
long long int numerator = n * n - 1;
long double ans = (numerator * 1.0) / 12;
return ans;
}
// Driver Code
int main()
{
int N = 5;
cout << fixed << setprecision(6)
<< find_Variance(N);
}
Java
// Java program to implement
// the above approach
class GFG{
// Function to calculate Varaince
// of first N natural numbers
static double find_Variance(int n)
{
long numerator = n * n - 1;
double ans = (numerator * 1.0) / 12;
return ans;
}
// Driver Code
public static void main(String[] args)
{
int N = 5;
System.out.println(find_Variance(N));
}
}
// This code is contributed by AnkThon
Python3
# Python3 program to implement
# the above approach
# Function to calculate Varaince
# of first N natural numbers
def find_Variance(n):
numerator = n * n - 1
ans = (numerator * 1.0) / 12
return ans
# Driver Code
if __name__ == '__main__':
N = 5
a = find_Variance(N)
print("{0:.6f}".format(a))
# This code is contributed by mohit kumar 29
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to calculate Varaince
// of first N natural numbers
static double find_Variance(int n)
{
long numerator = n * n - 1;
double ans = (numerator * 1.0) / 12;
return ans;
}
// Driver Code
public static void Main(string[] args)
{
int N = 5;
Console.WriteLine(find_Variance(N));
}
}
// This code is contributed by AnkThon
Javascript
2.000000
时间复杂度: O(1)
辅助空间: O(1)