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

Viewed 184

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

2 Answers

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)
    }

This could be one of the solution

I think this is efficient. I used it in my calculator app

I did that using java. Hope this will help

static void surd_form(long a) {
long i = 2;
long sq = 1;
long k = 4;
long p = 1;
while (k <= a) {
    if (a % i == 0) {
        if (a % k == 0) {
            a /= k;
            sq *= i;
        } else {
            a /= i;
            p *= i;
        }
    } else {
        i += 1;
    }
    k = i * i;
}
System.out.println(sq + "" + "√" + (a * p));
}
Related