C# :: Aufgabe #334 :: Lösung #4
4 Lösungen

#334
Primzahlzwillinge (p2 – p1 = 2)
Anfänger - C#
von JKooP
- 13.10.2020 um 08:52 Uhr
Ein Primzahlzwilling ist ein Paar aus Primzahlen, deren Abstand 2 ist.
Beispiele:
(3, 5), (5, 7), (11, 13), …, (569, 571), …
Schreibe eine Funktion/Methode, die alle Primzahlpaare kleiner 2000 ausgibt.
Viel Spaß
Beispiele:
(3, 5), (5, 7), (11, 13), …, (569, 571), …
Schreibe eine Funktion/Methode, die alle Primzahlpaare kleiner 2000 ausgibt.
Viel Spaß
#4

von JKooP (18090 Punkte)
- 01.11.2020 um 08:30 Uhr
// NET Core 3.x
C#-Code

using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApp2 { class Program { static void Main() => GetPrimePairs(2000).ToList().ForEach(x => Console.WriteLine(x)); static IEnumerable<(int, int)> GetPrimePairs(int max) { if (max >= 4) yield return (3, 5); for (int i = 6; i < max; i+=6) if (IsPrime(i - 1) && IsPrime(i + 1)) yield return (i - 1, i + 1); } static bool IsPrime(int n) => n switch { 2 => true, var k when k > 2 => !Enumerable.Range(2, (int)Math.Ceiling(Math.Sqrt(n))-1).Any(x => n % x == 0), _ => false }; } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1