C# :: Aufgabe #334
4 Lösungen
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ß
Lösungen:
using System;
using System.Collections.Generic;
namespace Aufgabe_334_Primzahlzwillinge
{
internal class Program
{
private static void Main(string[] args)
{
int berechneBisZahl = 2000;
List<int> primzahlen = new List<int>();
Console.WriteLine("Gibt Primzahlzwillinge bis zur Zahl 2000 aus\n\n");
for (int i = 2; i <= berechneBisZahl; i++)
{
if (IstPrimzahl(i))
{
primzahlen.Add(i);
}
}
int länge = primzahlen.Count - 1;
for (int i = 0; i < länge; i++)
{
if ((primzahlen[i+1]) - (primzahlen[i]) == 2)
{
Console.Write($" ({primzahlen[i]},{primzahlen[i+1]}),");
}
}
Console.ReadKey();
//Methode zm prüfen ob Zahl eine Primzahl ist
bool IstPrimzahl(int zuprüfendeZahl)
{
for (int i = 2; i < zuprüfendeZahl; i++)
{
if (zuprüfendeZahl % i == 0)
{
return false;
}
}
return true;
}
}
}
}using System;
using System.Collections.Generic;
namespace Primzahlzwillinge
{
class Program
{
static void Main(string[] args)
{
List<int> primzahlen = new List<int>();
int number = 0;
int max = 2000;
if (number == 2)
Console.WriteLine(2);
if (number % 2 == 0)
number++;
for (int i = number; i <= max; i += 2)
{
bool primzahl = true;
for (int j = 3; j < i; ++j)
{
if (i % j == 0)
{
primzahl = false;
break;
}
}
if (primzahl && i >= 2)
primzahlen.Add(i);
}
for (int i = 0; i + 1 < primzahlen.Count; i++)
{
if (primzahlen[i] + 2 == primzahlen[i + 1])
{
Console.WriteLine($"Zwillinge {primzahlen[i]} und {primzahlen[i + 1]}");
}
}
Console.ReadKey();
}
}
}
public class Program{
static void Main(string[] args){
bool isInt;
double lastNumber = 0;
for(double i = 0; i < 2000; i++){
isInt = i % 2 == 0;
if(isInt == false && i != 1|| isInt == true && i == 2){
isInt = i % 3 == 0;
if (isInt == false || isInt == true && i == 3){
isInt = i % 4 == 0;
if (isInt == false){
if(i - lastNumber == 2){
System.Console.WriteLine("(" + lastNumber + " | " + i + ")");
}
lastNumber = i;
}
}
}
}
}
}
}
// 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
};
}
}
