您得到了一系列(1 * 1)+(2 * 2)+(3 * 3)+(4 * 4)+(5 * 5)+…+(n * n),求出系列直到第n个学期。
例子 :
Input : n = 3
Output : 14
Explanation : 1 + 1/2^2 + 1/3^3
Input : n = 5
Output : 55
Explanation : (1*1) + (2*2) + (3*3) + (4*4) + (5*5)
C++
// CPP program to calculate the following series
#include
using namespace std;
// Function to calculate the following series
int Series(int n)
{
int i;
int sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
// Driver Code
int main()
{
int n = 3;
int res = Series(n);
cout<
C
// C program to calculate the following series
#include
// Function to calculate the following series
int Series(int n)
{
int i;
int sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
// Driver Code
int main()
{
int n = 3;
int res = Series(n);
printf("%d", res);
}
Java
// Java program to calculate the following series
import java.io.*;
class GFG {
// Function to calculate the following series
static int Series(int n)
{
int i;
int sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
// Driver Code
public static void main(String[] args)
{
int n = 3;
int res = Series(n);
System.out.println(res);
}
}
Python
# Python program to calculate the following series
def Series(n):
sums = 0
for i in range(1, n + 1):
sums += (i * i);
return sums
# Driver Code
n = 3
res = Series(n)
print(res)
C#
// C# program to calculate the following series
using System;
class GFG {
// Function to calculate the following series
static int Series(int n)
{
int i;
int sums = 0;
for (i = 1; i <= n; i++)
sums += (i * i);
return sums;
}
// Driver Code
public static void Main()
{
int n = 3;
int res = Series(n);
Console.Write(res);
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出 :
14
时间复杂度:O(n)
请参考下面的文章O(1)解决方案。
前n个自然数的平方和