Skip to content

Commit

Permalink
RootSample - divide out factors of 9
Browse files Browse the repository at this point in the history
  • Loading branch information
bobbymcr committed Aug 27, 2018
1 parent 69c7763 commit 21f8633
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
35 changes: 20 additions & 15 deletions projects/RootSample/RootSample.Core/RootTerm.cs
Expand Up @@ -5,10 +5,13 @@
namespace RootSample namespace RootSample
{ {
using System; using System;
using System.Collections.Generic;
using System.Text; using System.Text;


public struct RootTerm public struct RootTerm
{ {
private static readonly List<ushort> Primes = new List<ushort>() { 2, 3 };

private readonly int c; private readonly int c;
private readonly int x; private readonly int x;


Expand All @@ -18,33 +21,35 @@ public RootTerm(int n)
{ {
this.c = 0; this.c = 0;
this.x = 0; this.x = 0;
return;
} }
else
this.c = 1;
foreach (ushort p in Primes)
{ {
this.c = 1; int r;
while (true) while (true)
{ {
int r; int m = Math.DivRem(n, p * p, out r);
int m = Math.DivRem(n, 4, out r);
if (r != 0) if (r != 0)
{ {
break; break;
} }


n = m; n = m;
this.c *= 2; this.c *= p;
} }
}


int s = (int)Math.Sqrt(n); int s = (int)Math.Sqrt(n);
if (s * s == n) if (s * s == n)
{ {
this.x = 1; this.x = 1;
this.c *= s; this.c *= s;
} }
else else
{ {
this.x = n; this.x = n;
}
} }
} }


Expand Down
9 changes: 9 additions & 0 deletions projects/RootSample/RootSample.Test/RootTermTest.cs
Expand Up @@ -31,5 +31,14 @@ public void FactorsOfFour(int n, string expected)
{ {
new RootTerm(n).ToString().Should().Be(expected, "sqrt({0}) is {1}", n, expected); new RootTerm(n).ToString().Should().Be(expected, "sqrt({0}) is {1}", n, expected);
} }

[Theory]
[InlineData(18, "3*sqrt(2)")]
[InlineData(243, "9*sqrt(3)")]
[InlineData(2147483646, "3*sqrt(238609294)")]
public void FactorsOfNine(int n, string expected)
{
new RootTerm(n).ToString().Should().Be(expected, "sqrt({0}) is {1}", n, expected);
}
} }
} }

0 comments on commit 21f8633

Please sign in to comment.