Skip to content
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
Expand Up @@ -28,7 +28,7 @@ public async Task Should_Calculate(string arg, string expected)
[MethodDataSource(nameof(Eulers))]
public async Task Should_CalculateEuler(int n, int expected)
{
var result = Problem072.EulersTotient(n);
var result = Problem072.TotientSieve(A000010.Length)[n];

await Assert.That(result).IsEqualTo(expected);
}
Expand Down
36 changes: 26 additions & 10 deletions ProjectEuler/Problems/001-100/71-80/Problem072.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Fractions;

namespace ProjectEuler.Problems._001_100._71_80;

/// <summary>
Expand All @@ -26,25 +24,43 @@ public Task<string> CalculateAsync(string[] args)
/// </summary>
public static long Phi(int n)
{
var totients = TotientSieve(n);

var sum = 0L;
for (var i = 1; i <= n; i++)
{
sum += EulersTotient(i);
sum += totients[i];
}

return sum;
}

public static int EulersTotient(int n)
/// <summary>
/// Euler's totient of every number in [0, n], via Euler's product formula
/// applied one prime at a time.
/// </summary>
public static int[] TotientSieve(int n)
{
// Euler's product formula
var factors = n.PrimeFactors();
var product = new Fraction(n, 1);
foreach (var factor in factors)
var phi = new int[n + 1];
for (var i = 0; i <= n; i++)
{
product *= Fraction.One - new Fraction(1, factor, false);
phi[i] = i;
}

for (var p = 2; p <= n; p++)
{
if (phi[p] != p)
{
// p was already reduced by a smaller prime, so it is composite
continue;
}

for (var m = p; m <= n; m += p)
{
phi[m] -= phi[m] / p;
}
}

return product.ToInt32();
return phi;
}
}
Loading