方形金字塔数表示第一自然数的平方和。前几个Square金字塔数是1、5、14、30、55、91、140、204、285、385、506,…
在几何上,这些数字表示要堆叠以形成具有方形底角的金字塔的球的数量。请查看此Wiki图像以获取更多清晰度。
给定数字s(1 <= s <= 1000000000)。如果s是前n个自然数的平方和,则打印n,否则打印-1。
例子 :
Input : 14
Output : 3
Explanation : 1*1 + 2*2 + 3*3 = 14
Input : 26
Output : -1
一个简单的解决方案是遍历所有从1开始的数字,计算当前总和。如果当前总和等于给定总和,则返回true,否则返回false。
C++
// C++ program to check if a
// given number is sum of
// squares of natural numbers.
#include
using namespace std;
// Function to find if the
// given number is sum of
// the squares of first n
// natural numbers
int findS(int s)
{
int sum = 0;
// Start adding squares of
// the numbers from 1
for (int n = 1; sum < s; n++)
{
sum += n * n;
// If sum becomes equal to s
// return n
if (sum == s)
return n;
}
return -1;
}
// Drivers code
int main()
{
int s = 13;
int n = findS(s);
n == -1 ? cout << "-1" : cout << n;
return 0;
}
Java
// Java program to check if a
// given number is sum of
// squares of natural numbers.
class GFG
{
// Function to find if the
// given number is sum of
// the squares of first
// n natural numbers
static int findS(int s)
{
int sum = 0;
// Start adding squares of
// the numbers from 1
for (int n = 1; sum < s; n++)
{
sum += n * n;
// If sum becomes equal to s
// return n
if (sum == s)
return n;
}
return -1;
}
// Drivers code
public static void main(String[] args)
{
int s = 13;
int n = findS(s);
if (n == -1)
System.out.println("-1");
else
System.out.println(n);
}
}
Python3
# Python3 program to find if
# the given number is sum of
# the squares of first
# n natural numbers
# Function to find if the given
# number is sum of the squares
# of first n natural numbers
def findS (s):
_sum = 0
n = 1
# Start adding squares of
# the numbers from 1
while(_sum < s):
_sum += n * n
n+= 1
n-= 1
# If sum becomes equal to s
# return n
if _sum == s:
return n
return -1
# Driver code
s = 13
n = findS (s)
if n == -1:
print("-1")
else:
print(n)
C#
// C# program to check if a given
// number is sum of squares of
// natural numbers.
using System;
class GFG
{
// Function to find if the given
// number is sum of the squares
// of first n natural numbers
static int findS(int s)
{
int sum = 0;
// Start adding squares of
// the numbers from 1
for (int n = 1; sum < s; n++)
{
sum += n * n;
// If sum becomes equal
// to s return n
if (sum == s)
return n;
}
return -1;
}
// Drivers code
public static void Main()
{
int s = 13;
int n = findS(s);
if(n == -1)
Console.Write("-1") ;
else
Console.Write(n);
}
}
// This code is contribute by
// Smitha Dinesh Semwal
PHP
Javascript
输出 :
-1
另一种解决方案是使用牛顿拉夫森法。
我们知道,前n个自然数的平方和为n *(n + 1)*(2 * n +1)/ 6 。
我们可以写解决方案为
k *(k + 1)*(2 * k +1)/ 6 = s
k *(k + 1)*(2 * k +1)– 6s = 0
我们可以使用牛顿拉夫森法找到上述三次方程的根,然后检查根是否为整数。