Permalink
Browse files

RootSample - divide out factors of 4

  • Loading branch information...
bobbymcr committed Aug 27, 2018
1 parent c106472 commit 69c77635a4e426a0de44f2d475431ab7dedf49cb
@@ -5,16 +5,71 @@
namespace RootSample
{
using System;
using System.Text;
public struct RootTerm
{
private readonly int n;
private readonly int c;
private readonly int x;
public RootTerm(int n)
{
this.n = (int)Math.Sqrt(n);
if (n == 0)
{
this.c = 0;
this.x = 0;
}
else
{
this.c = 1;
while (true)
{
int r;
int m = Math.DivRem(n, 4, out r);
if (r != 0)
{
break;
}
n = m;
this.c *= 2;
}
int s = (int)Math.Sqrt(n);
if (s * s == n)
{
this.x = 1;
this.c *= s;
}
else
{
this.x = n;
}
}
}
public override string ToString() => this.n.ToString();
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (this.c != 1)
{
sb.Append(this.c);
}
if (this.x > 1)
{
sb.Append('*');
sb.Append("sqrt(");
sb.Append(this.x);
sb.Append(')');
}
if (sb.Length == 0)
{
return "1";
}
return sb.ToString();
}
}
}
@@ -21,5 +21,15 @@ public void PerfectSquares(int n, string expected)
{
new RootTerm(n).ToString().Should().Be(expected, "sqrt({0}) is {1}", n, expected);
}
[Theory]
[InlineData(8, "2*sqrt(2)")]
[InlineData(24, "2*sqrt(6)")]
[InlineData(262084, "2*sqrt(65521)")]
[InlineData(2147483644, "2*sqrt(536870911)")]
public void FactorsOfFour(int n, string expected)
{
new RootTerm(n).ToString().Should().Be(expected, "sqrt({0}) is {1}", n, expected);
}
}
}

0 comments on commit 69c7763

Please sign in to comment.