This program will calculate square root with two classes. It is really a fascinating program, due to the fact that it uses precalculation in the class SqrtPrecalculated.
Thus, if you need plenty of calculations, once the values are precalculated it will simply give you the values and not calculate them once again. Thus, it is really fast. Actually, you will not notice it unless you are using a really slow PC or you write a separate code to test the calculation time of a root. But anyway, this is the content of the class sqrtPrecalculated.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class SqrtPrecalculated { public const int MaxValue = 100000; private static int[] sqrtValues; static SqrtPrecalculated() { sqrtValues = new int[MaxValue + 1]; for (int i = 0; i < sqrtValues.Length; i++) { sqrtValues[i] = (int)Math.Sqrt(i); } } public static int GetSqrt(int value) { if ((value < 0) || (value > MaxValue)) { throw new ArgumentOutOfRangeException(string.Format("The argument should be in range [0..{0}].", MaxValue)); } return sqrtValues[value]; } } |
What this class does?
1. We have initialization of a constant MaxValue and Array sqrtValues.
2. In the method SqrtPrecalculated we recalculate all the square roots from 0 to 100000 (we reach this number in the array by using the +1, due to the fact that the arrays start from 0.
3. In the method GetSqrt, we check about the size of the given number – if it is not between 0 and 100000 we return exception.
4. If it is OK, we return the precalculated value.
The main method is in another class.
It looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; class SqrtTest { static void Main() { int Z; do { Console.WriteLine("Please, enter a number to be squared or enter 0 to exit:"); int x = int.Parse(Console.ReadLine()); Console.WriteLine(SqrtPrecalculated.GetSqrt(x)); Z = x; } while (Z != 0); Console.WriteLine("Thank you for visiting vitoshacademy.com"); Thread.Sleep(1000); } } |
It simply asks for input of a number and sets it as attribute of the method “SqrtPrecalculated”. Then it returns the value.
If you give 0 as input, the program exits the while/do loop and thanks you for visiting my site!
If you want to see the program in action, you may download it from here.
Some of the code of the current article is part of the free Bulgarian C# programming book.