Find no of square between two numbers in c#.

   /* Watson gives two integers(A and B ) to Sherlock and asks if he can count the number of square integers between A and B(both inclusive).

Note: A square integer is an integer which is the square of any integer.For example, 1, 4, 9, and 16 are some of the square integers as they are squares of 1, 2, 3, and 4, respectively.
Input Format
The first line contains T, the number of test cases. T test cases follow, each in a new line.
Each test case contains two space-separated integers denoting A and B.
Constraints
1<=T<=100
1<=A<=B<=10^9


Output Format

For each test case, print the required answer in a new line.
Sample Input
2
3 9
17 24
Sample Output
2
0
Explanation
Test Case #00: In range[3,9] ,4  and 9 are the two square numbers.
Test Case #01: In range [17 24], there are no square numbers.*/


using System;
using System.Linq;

namespace HackerDemo
{

   public class NoOFSquareNumbers
    {
        public void GetnoOfSquareNumber()
        {
            Console.WriteLine("Enter no of test case is required");
            int t = Convert.ToInt32(Console.ReadLine());
            for (int a0 = 0; a0 < t; a0++)
            {
                 Console.WriteLine("Enter first two numbers");
                string line = Console.ReadLine();
                string[] tokens = line.Split(' ');
                int[] numbers = Array.ConvertAll(tokens, int.Parse);
                int fn = 0, sn = 0;
                if (numbers.Count() == 2)
                {
                    fn = numbers[0];
                    sn = numbers[1];
                }
                int count = 0, gn = fn > sn ? fn : sn;

                for (int i = fn < sn ? fn : sn; i <= gn; i++)
                {
                    if (isSquareNumber(i))
                    {
                        count++;
                    }
                }
                Console.WriteLine(count);
            }
        }

        private bool isSquareNumber(int n)
        {
            double result = Math.Sqrt(n);
            return result % 1 == 0;
        }
    }
}

No comments:

Post a Comment