Skip to content

#41 Factorization #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System.Collections.Generic;
using FluentAssertions;
using Xunit;

namespace Algorithms.Tests.FactorizationTests
{
public class FactorizationTest
{
[Fact]
public void GetFactors_FactorizationOf825_ReturnCollection()
{
var expected = new List<int>{3, 5, 5, 11};

var result = Factorization.GetFactorsOf(825);

result.Should().BeEquivalentTo(expected);
}

[Fact]
public void GetFactors_FactorizationOf1386_ReturnCollection()
{
var expected = new List<int> { 2, 3, 3, 7, 11 };

var result = Factorization.GetFactorsOf(1386);

result.Should().BeEquivalentTo(expected);
}

[Fact]
public void GetFactors_FactorizationOf0_ReturnCollectionWith0()
{
var result = Factorization.GetFactorsOf(0);

result.Should().BeEquivalentTo(0);
}

[Fact]
public void GetFactors_FactorizationOfNegative_ReturnCollectionWith0()
{
var result = Factorization.GetFactorsOf(-1);

result.Should().BeEquivalentTo(0);
}
}
}
67 changes: 67 additions & 0 deletions Algorithms/Algorithms/Factorization/Factorization.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
public static class Factorization
{
public static IEnumerable<int> GetFactorsOf(int input)
{
if (input < 0)
return new [] {0};

var first = GetPrimes()
.TakeWhile(x => x <= Math.Sqrt(input))
.FirstOrDefault(x => input % x == 0);

var result = first == 0
? new[] { input }
: new[] { first }.Concat(GetFactorsOf(input / first));

return result;
}

private static IEnumerable<int> GetSequence()
{
yield return 2;
yield return 3;

var k = 1;
while (k > 0)
{
yield return 6 * k - 1;
yield return 6 * k + 1;
k++;
}
}

private static IEnumerable<int> GetPrimes()
{
var memoized = new List<int>();
var sqrt = 1;
var primes = GetSequence().Where(x =>
{
sqrt = GetSqrtCeiling(x, sqrt);
return memoized
.TakeWhile(y => y <= sqrt)
.All(y => x % y != 0);
});

foreach (var prime in primes)
{
yield return prime;
memoized.Add(prime);
}
}

private static int GetSqrtCeiling(int value, int start)
{
while (start * start < value)
{
start++;
}
return start;
}
}
}