Create a 500 element array and load the array with a series of numbers starting at the first position that is the square of the index. For example, at position 0 would be 0, at position 1 would be 1, at position 2 would be 4, at position 3 would be 9…. Etc. Ask the user for a number between 0 and 250,000 and let them know if that number is a square. Employ a binary search.
using System;
using System.Linq;
using System.Text;
class Program
{
static void Main()
{
int[] array = Enumerable.Range(0, 499).Select(x => x * x).ToArray();
Console.Write("Enter a number between (0 - 250000): ");
int number = int.Parse(Console.ReadLine());
int min = 0;
int max = array.Length - 1;
int? square = null;
while (min <= max)
{
int mid = (min + max) / 2;
if (number == array[mid])
{
square = mid++;
break;
}
else if (number < array[mid])
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
if(square.HasValue)
Console.WriteLine($"Square of {square}");
else
Console.WriteLine("Number is not a square.");
}
}
Comments
Leave a comment