Finding Next Perfect Square using math function.
Write a function named nextPerfectSquare that returns the first perfect square that is greater that its integer argument. A perfect square is an integer that is equal to some integer squared. For example 16 is a perfect square because 16=4*4. However 15 is not a perfect square because there is no integer n such that 15=n*n.
Examples:-
n | next perfect square |
---|---|
6 | 9 |
36 | 49 |
0 | 1 |
-5 | 0 |
Solution:-
using System;
namespace perfectSquare
{
class Program
{
static int nextPerfectSquare(int n)
{
{
int nextN = (int)Math.Floor(Math.Sqrt(n)) + 1;
return nextN * nextN;
}
}
public static void Main()
{
string number;
Console.WriteLine("Enter a number:");
number=Console.ReadLine();
int numb = Convert.ToInt32(number);
if(numb<0)
{
Console.WriteLine("0");
}
else if(numb==0)
{
Console.WriteLine("1");
}
else
{
Console.WriteLine(nextPerfectSquare(numb));
}
}
}
}
Output:-