C# Find the next perfect square!

You might know some pretty large perfect squares. But what about the NEXT one?

Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.

If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive.


findNextSquare(121) --> returns 144
findNextSquare(625) --> returns 676
findNextSquare(114) --> returns -1 since 114 is not a perfect

Solution :

using System;

public class perfectSquare
 public static long FindNextSquare(long num)
 double result = Math.Sqrt(num);
 bool isSquare = result % 1 == 0;
 if (isSquare == true)
 result *= result;
 long l = Convert.ToInt64(result);
 return l;
 return -1;

Example Tests:

using NUnit.Framework;
using System;

public class Tests
 [TestCase(155, Result=-1)]
 [TestCase(121, Result=144)]
 [TestCase(625, Result=676)]
 [TestCase(319225, Result=320356)]
 [TestCase(15241383936, Result=15241630849)]
 public static long FixedTest(long num)
 return Kata.FindNextSquare(num);



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s