Search code examples
c#algebrasqrt

How do you leave roots in surd form in c#?


Example a: √12 =2√3

Example b: √16 = 4

I am trying to get both.

Whilst I can of course use Math.Sqrt(4) to achieve outcome b, I've no idea how to achieve a, or further how to get both to work simultaneously which is the goal. How do I achieve this type of simplification in C#?

I have tried several libraries including MathNet, Symbolics and NCalc with no success. This post may have solved it in c++, although I do not know for sure. My attempts at converting that solution to even see if it worked were very much a failure:

var outside_root = 1;
var inside_root = 800;
var d = 2;
while (d * d <= inside_root)
    if (inside_root % (d * d) == 0)  //# inside_root evenly divisible by d * d
    {
        inside_root = inside_root / (d * d);
        outside_root = (outside_root * d);
    }
while (d * d > inside_root) { 
d = (d + 1);}

Thank you for any help


Solution

  • The given C++ can be translated into C# without a lot of changes. Also a couple of modifications can be made to the original algorithm to reduce number of multiplications and increase overall performance:

        static (int, int) Sqrt2(int n)
        {
            int m = 1, d = 2;
    
            int dSquared;
            while ((dSquared = d * d) <= n)
            {
                while ((n % dSquared) == 0)
                {
                    n /= dSquared;
                    m *= d;
                }
                d++;
            }
    
            return (m, n);
        }
    
        static void Main(string[] args)
        {
            Console.WriteLine(Sqrt2(12)); // prints (2, 3)
            Console.WriteLine(Sqrt2(16)); // prints (4, 1)
            Console.WriteLine(Sqrt2(13)); // prints (1, 13)
        }