Answer to Question #332267 in HTML/JavaScript Web Application for deepanshu

Question #332267

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. 


1
Expert's answer
2022-04-22T13:30:37-0400
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.");
    }


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS