Skip to content

Commit

Permalink
RootSample - divide out factors of 4
Browse files Browse the repository at this point in the history
  • Loading branch information
bobbymcr committed Aug 27, 2018
1 parent c106472 commit 69c7763
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 3 deletions.
61 changes: 58 additions & 3 deletions projects/RootSample/RootSample.Core/RootTerm.cs
Expand Up @@ -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();
}
}
}
10 changes: 10 additions & 0 deletions projects/RootSample/RootSample.Test/RootTermTest.cs
Expand Up @@ -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.