Honaker primes: Difference between revisions

Content added Content deleted
(Add Scala implementation)
(Add C# implementation)
Line 285: Line 285:


and the 10,000th: (286,069, 4,043,749)
and the 10,000th: (286,069, 4,043,749)
</pre>

=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Linq;

public class HonakerPrimes
{
private static List<int> primes = new List<int>();
private static int honakerIndex = 0;
private static int primeIndex = 0;

public static void Main(string[] args)
{
SievePrimes(5_000_000);

Console.WriteLine("The first 50 Honaker primes (honaker index: prime index, prime):");
for (int i = 1; i <= 50; i++)
{
Console.Write($"{NextHonakerPrime()}{(i % 5 == 0 ? "\n" : " ")}");
}
for (int i = 51; i < 10_000; i++)
{
NextHonakerPrime();
}
Console.WriteLine();
Console.WriteLine($"The 10,000th Honaker prime is: {NextHonakerPrime()}");
}

private static HonakerPrime NextHonakerPrime()
{
honakerIndex++;
primeIndex++;
while (DigitalSum(primeIndex) != DigitalSum(primes[primeIndex - 1]))
{
primeIndex++;
}
return new HonakerPrime(honakerIndex, primeIndex, primes[primeIndex - 1]);
}

private static int DigitalSum(int number)
{
return number.ToString().Select(c => c - '0').Sum();
}

private static void SievePrimes(int limit)
{
primes.Add(2);
var halfLimit = (limit + 1) / 2;
bool[] composite = new bool[halfLimit];
for (int i = 1, p = 3; i < halfLimit; p += 2, i++)
{
if (!composite[i])
{
primes.Add(p);
for (int a = i + p; a < halfLimit; a += p)
{
composite[a] = true;
}
}
}
}

private class HonakerPrime
{
public int HonakerIndex { get; }
public int PrimeIndex { get; }
public int Prime { get; }

public HonakerPrime(int honakerIndex, int primeIndex, int prime)
{
HonakerIndex = honakerIndex;
PrimeIndex = primeIndex;
Prime = prime;
}

public override string ToString() => $"({HonakerIndex}: {PrimeIndex}, {Prime})";
}
}
</syntaxhighlight>
{{out}}
<pre>
The first 50 Honaker primes (honaker index: prime index, prime):
(1: 32, 131) (2: 56, 263) (3: 88, 457) (4: 175, 1039) (5: 176, 1049)
(6: 182, 1091) (7: 212, 1301) (8: 218, 1361) (9: 227, 1433) (10: 248, 1571)
(11: 293, 1913) (12: 295, 1933) (13: 323, 2141) (14: 331, 2221) (15: 338, 2273)
(16: 362, 2441) (17: 377, 2591) (18: 386, 2663) (19: 394, 2707) (20: 397, 2719)
(21: 398, 2729) (22: 409, 2803) (23: 439, 3067) (24: 446, 3137) (25: 457, 3229)
(26: 481, 3433) (27: 499, 3559) (28: 508, 3631) (29: 563, 4091) (30: 571, 4153)
(31: 595, 4357) (32: 599, 4397) (33: 635, 4703) (34: 637, 4723) (35: 655, 4903)
(36: 671, 5009) (37: 728, 5507) (38: 751, 5701) (39: 752, 5711) (40: 755, 5741)
(41: 761, 5801) (42: 767, 5843) (43: 779, 5927) (44: 820, 6301) (45: 821, 6311)
(46: 826, 6343) (47: 827, 6353) (48: 847, 6553) (49: 848, 6563) (50: 857, 6653)

The 10,000th Honaker prime is: (10000: 286069, 4043749)

</pre>
</pre>