saber que programa primos primo para numeros numero form diga algoritmo c# primes primality-test

que - numeros primos c# windows form



Verifica si el número es el número primo (19)

Los números primos son números que son más grandes que uno y no se pueden dividir de manera uniforme por ningún otro número, excepto 1 y sí mismo.

@Este programa le mostrará que el número dado es primo o no, y le mostrará el número no principal que es divisible por (un número) que es en lugar de 1 o sí mismo? @

Console.Write("Please Enter a number: "); int number = int.Parse(Console.ReadLine()); int count = 2; // this is initial count number which is greater than 1 bool prime = true; // used Boolean value to apply condition correctly int sqrtOfNumber = (int)Math.Sqrt(number); // square root of input number this would help to simplify the looping. while (prime && count <= sqrtOfNumber) { if ( number % count == 0) { Console.WriteLine($"{number} isn''t prime and it divisible by number {count}"); // this will generate a number isn''t prime and it is divisible by a number which is rather than 1 or itself and this line will proves why it''s not a prime number. prime = false; } count++; } if (prime && number > 1) { Console.WriteLine($"{number} is a prime number"); } else if (prime == true) // if input is 1 or less than 1 then this code will generate { Console.WriteLine($"{number} isn''t a prime"); }

Me gustaría preguntar si esta es una forma correcta de verificar si el número es primo o no. porque leí que 0 y 1 NO son un número primo.

int num1; Console.WriteLine("Accept number:"); num1 = Convert.ToInt32(Console.ReadLine()); if (num1 == 0 || num1 == 1) { Console.WriteLine(num1 + " is not prime number"); Console.ReadLine(); } else { for (int a = 2; a <= num1 / 2; a++) { if (num1 % a == 0) { Console.WriteLine(num1 + " is not prime number"); return; } } Console.WriteLine(num1 + " is a prime number"); Console.ReadLine(); }


Aquí hay un buen ejemplo . Voy a dejar caer el código aquí en caso de que el sitio se caiga un día.

using System; class Program { static void Main() { // // Write prime numbers between 0 and 100. // Console.WriteLine("--- Primes between 0 and 100 ---"); for (int i = 0; i < 100; i++) { bool prime = PrimeTool.IsPrime(i); if (prime) { Console.Write("Prime: "); Console.WriteLine(i); } } // // Write prime numbers between 10000 and 10100 // Console.WriteLine("--- Primes between 10000 and 10100 ---"); for (int i = 10000; i < 10100; i++) { if (PrimeTool.IsPrime(i)) { Console.Write("Prime: "); Console.WriteLine(i); } } } }

Aquí está la clase que contiene el método IsPrime :

using System; public static class PrimeTool { public static bool IsPrime(int candidate) { // Test whether the parameter is a prime number. if ((candidate & 1) == 0) { if (candidate == 2) { return true; } else { return false; } } // Note: // ... This version was changed to test the square. // ... Original version tested against the square root. // ... Also we exclude 1 at the end. for (int i = 3; (i * i) <= candidate; i += 2) { if ((candidate % i) == 0) { return false; } } return candidate != 1; } }


Aquí hay una buena forma de hacerlo.

static bool IsPrime(int n) { if (n > 1) { return Enumerable.Range(1, n).Where(x => n%x == 0) .SequenceEqual(new[] {1, n}); } return false; }

Y una forma rápida de escribir su programa será:

for (;;) { Console.Write("Accept number: "); int n = int.Parse(Console.ReadLine()); if (IsPrime(n)) { Console.WriteLine("{0} is a prime number",n); } else { Console.WriteLine("{0} is not a prime number",n); } }


Basado en la respuesta de @Michael, pero verifica los números negativos y calcula el cuadrado de forma incremental

public static bool IsPrime( int candidate ) { if ( candidate % 2 <= 0 ) { return candidate == 2; } int power2 = 9; for ( int divisor = 3; power2 <= candidate; divisor += 2 ) { if ( candidate % divisor == 0 ) return false; power2 += divisor * 4 + 4; } return true; }


Creo que esta es una forma sencilla para los principiantes:

using System; using System.Numerics; public class PrimeChecker { public static void Main() { // Input Console.WriteLine("Enter number to check is it prime: "); BigInteger n = BigInteger.Parse(Console.ReadLine()); bool prime = false; // Logic if ( n==0 || n==1) { Console.WriteLine(prime); } else if ( n==2 ) { prime = true; Console.WriteLine(prime); } else if (n>2) { IsPrime(n, prime); } } // Method public static void IsPrime(BigInteger n, bool prime) { bool local = false; for (int i=2; i<=(BigInteger)Math.Sqrt((double)n); i++) { if (n % i == 0) { local = true; break; } } if (local) { Console.WriteLine(prime); } else { prime = true; Console.WriteLine(prime); } } }


El algoritmo en la función consiste en probar si n es un múltiplo de cualquier número entero entre 2 y sqrt (n). Si no es así, se devuelve True, lo que significa que el número (n) es un número primo; de lo contrario, se devuelve False, lo que significa n divide un número que está entre 2 y la parte entera del piso de sqrt (n).

Versión recursiva

// Always call it as isPrime(n,2) private static bool isPrime(int n, int k) { if (k * k <= n) { if ((n % k) == 0) return false; else return isPrime(n, k + 1); } else return true; }


El algoritmo en la función consiste en probar si n es un múltiplo de cualquier número entero entre 2 y sqrt (n). Si no es así, se devuelve True, lo que significa que el número (n) es un número primo; de lo contrario, se devuelve False, lo que significa n divide un número que está entre 2 y la parte entera del piso de sqrt (n).

private static bool isPrime(int n) { int k = 2; while (k * k <= n) { if ((n % k) == 0) return false; else k++; } return true; }


Encuentre este ejemplo en un libro y piense que es una solución bastante elegante.

static void Main(string[] args) { Console.Write("Enter a number: "); int theNum = int.Parse(Console.ReadLine()); if (theNum < 3) // special case check, less than 3 { if (theNum == 2) { // The only positive number that is a prime Console.WriteLine("{0} is a prime!", theNum); } else { // All others, including 1 and all negative numbers, // are not primes Console.WriteLine("{0} is not a prime", theNum); } } else { if (theNum % 2 == 0) { // Is the number even? If yes it cannot be a prime Console.WriteLine("{0} is not a prime", theNum); } else { // If number is odd, it could be a prime int div; // This loop starts and 3 and does a modulo operation on all // numbers. As soon as there is no remainder, the loop stops. // This can be true under only two circumstances: The value of // div becomes equal to theNum, or theNum is divided evenly by // another value. for (div = 3; theNum % div != 0; div += 2) ; // do nothing if (div == theNum) { // if theNum and div are equal it must be a prime Console.WriteLine("{0} is a prime!", theNum); } else { // some other number divided evenly into theNum, and it is not // itself, so it is not a prime Console.WriteLine("{0} is not a prime", theNum); } } } Console.ReadLine(); }


Esta versión calcula una lista de primos raíces cuadradas y solo comprueba si la lista de números primos debajo de la raíz cuadrada, y utiliza una búsqueda binaria en la lista para encontrar primos conocidos. Pasé por los primeros 1.000.000 de números primos y tardé unos 7 segundos.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { //test(); testMax(); Console.ReadLine(); } static void testMax() { List<int> CheckPrimes = Enumerable.Range(2, 1000000).ToList(); PrimeChecker pc = new PrimeChecker(1000000); foreach (int i in CheckPrimes) { if (pc.isPrime(i)) { Console.WriteLine(i); } } } } public class PrimeChecker{ public List<int> KnownRootPrimesList; public int HighestKnownPrime = 3; public PrimeChecker(int Max=1000000){ KnownRootPrimesList = new List<int>(); KnownRootPrimesList.Add(2); KnownRootPrimesList.Add(3); isPrime(Max); } public bool isPrime(int value) { int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value)))); if(srt > HighestKnownPrime) { for(int i = HighestKnownPrime + 1; i <= srt; i++) { if (i > HighestKnownPrime) { if(isPrimeCalculation(i)) { KnownRootPrimesList.Add(i); HighestKnownPrime = i; } } } } bool isValuePrime = isPrimeCalculation(value); return(isValuePrime); } private bool isPrimeCalculation(int value) { if (value < HighestKnownPrime) { if (KnownRootPrimesList.BinarySearch(value) > -1) { return (true); } else { return (false); } } int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value)))); bool isPrime = true; List<int> CheckList = KnownRootPrimesList.ToList(); if (HighestKnownPrime + 1 < srt) { CheckList.AddRange(Enumerable.Range(HighestKnownPrime + 1, srt)); } foreach(int i in CheckList) { isPrime = ((value % i) != 0); if(!isPrime) { break; } } return (isPrime); } public bool isPrimeStandard(int value) { int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value)))); bool isPrime = true; List<int> CheckList = Enumerable.Range(2, srt).ToList(); foreach (int i in CheckList) { isPrime = ((value % i) != 0); if (!isPrime) { break; } } return (isPrime); } } }


Esto es básicamente una implementación de una brillante sugerencia hecha por Eric Lippert en algún lugar de arriba.

public static bool isPrime(int number) { if (number == 1) return false; if (number == 2 || number == 3 || number == 5) return true; if (number % 2 == 0 || number % 3 == 0 || number % 5 == 0) return false; var boundary = (int)Math.Floor(Math.Sqrt(number)); // You can do less work by observing that at this point, all primes // other than 2 and 3 leave a remainder of either 1 or 5 when divided by 6. // The other possible remainders have been taken care of. int i = 6; // start from 6, since others below have been handled. while (i <= boundary) { if (number % (i + 1) == 0 || number % (i + 5) == 0) return false; i += 6; } return true; }


Estoy tratando de sacar algo de eficiencia de la salida anticipada cuando uso Any () ...

public static bool IsPrime(long n) { if (n == 1) return false; if (n == 3) return true; //Even numbers are not primes if (n % 2 == 0) return false; return !Enumerable.Range(2, Convert.ToInt32(Math.Ceiling(Math.Sqrt(n)))) .Any(x => n % x == 0); }


Implementé un método diferente para verificar los primos porque:

  • La mayoría de estas soluciones siguen iterando innecesariamente en el mismo múltiplo (por ejemplo, verifican 5, 10 y luego 15, algo que un solo% por 5 probará).
  • Un% por 2 manejará todos los números pares (todos los números enteros que terminen en 0, 2, 4, 6 u 8).
  • Un% por 5 manejará todos los múltiplos de 5 (todos los enteros que terminan en 5).
  • Lo que queda es probar las divisiones pares por enteros que terminan en 1, 3, 7 o 9. Pero la belleza es que podemos incrementar de 10 en 10, en lugar de subir en 2, y demostraré una solución que es enhebrado
  • Los otros algoritmos no están enhebrados, por lo que no aprovechan sus núcleos tanto como yo esperaba.
  • También necesitaba soporte para primos realmente grandes, así que necesitaba usar el tipo de datos BigInteger en lugar de int, long, etc.

Aquí está mi implementación:

public static BigInteger IntegerSquareRoot(BigInteger value) { if (value > 0) { int bitLength = value.ToByteArray().Length * 8; BigInteger root = BigInteger.One << (bitLength / 2); while (!IsSquareRoot(value, root)) { root += value / root; root /= 2; } return root; } else return 0; } private static Boolean IsSquareRoot(BigInteger n, BigInteger root) { BigInteger lowerBound = root * root; BigInteger upperBound = (root + 1) * (root + 1); return (n >= lowerBound && n < upperBound); } static bool IsPrime(BigInteger value) { Console.WriteLine("Checking if {0} is a prime number.", value); if (value < 3) { if (value == 2) { Console.WriteLine("{0} is a prime number.", value); return true; } else { Console.WriteLine("{0} is not a prime number because it is below 2.", value); return false; } } else { if (value % 2 == 0) { Console.WriteLine("{0} is not a prime number because it is divisible by 2.", value); return false; } else if (value == 5) { Console.WriteLine("{0} is a prime number.", value); return true; } else if (value % 5 == 0) { Console.WriteLine("{0} is not a prime number because it is divisible by 5.", value); return false; } else { // The only way this number is a prime number at this point is if it is divisible by numbers ending with 1, 3, 7, and 9. AutoResetEvent success = new AutoResetEvent(false); AutoResetEvent failure = new AutoResetEvent(false); AutoResetEvent onesSucceeded = new AutoResetEvent(false); AutoResetEvent threesSucceeded = new AutoResetEvent(false); AutoResetEvent sevensSucceeded = new AutoResetEvent(false); AutoResetEvent ninesSucceeded = new AutoResetEvent(false); BigInteger squareRootedValue = IntegerSquareRoot(value); Thread ones = new Thread(() => { for (BigInteger i = 11; i <= squareRootedValue; i += 10) { if (value % i == 0) { Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i); failure.Set(); } } onesSucceeded.Set(); }); ones.Start(); Thread threes = new Thread(() => { for (BigInteger i = 3; i <= squareRootedValue; i += 10) { if (value % i == 0) { Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i); failure.Set(); } } threesSucceeded.Set(); }); threes.Start(); Thread sevens = new Thread(() => { for (BigInteger i = 7; i <= squareRootedValue; i += 10) { if (value % i == 0) { Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i); failure.Set(); } } sevensSucceeded.Set(); }); sevens.Start(); Thread nines = new Thread(() => { for (BigInteger i = 9; i <= squareRootedValue; i += 10) { if (value % i == 0) { Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i); failure.Set(); } } ninesSucceeded.Set(); }); nines.Start(); Thread successWaiter = new Thread(() => { AutoResetEvent.WaitAll(new WaitHandle[] { onesSucceeded, threesSucceeded, sevensSucceeded, ninesSucceeded }); success.Set(); }); successWaiter.Start(); int result = AutoResetEvent.WaitAny(new WaitHandle[] { success, failure }); try { successWaiter.Abort(); } catch { } try { ones.Abort(); } catch { } try { threes.Abort(); } catch { } try { sevens.Abort(); } catch { } try { nines.Abort(); } catch { } if (result == 1) { return false; } else { Console.WriteLine("{0} is a prime number.", value); return true; } } } }

Actualización : si desea implementar una solución con división de prueba más rápidamente, podría considerar tener un caché de números primos. Un número solo es primo si no es divisible por otros números primos que tienen el valor de su raíz cuadrada . Aparte de eso, puede considerar usar la versión probabilística de la prueba de primalidad Miller-Rabin para verificar la primalidad de un número si está tratando con valores suficientemente grandes (tomados del Código Rosetta en caso de que el sitio se caiga):

// Miller-Rabin primality test as an extension method on the BigInteger type. // Based on the Ruby implementation on this page. public static class BigIntegerExtensions { public static bool IsProbablePrime(this BigInteger source, int certainty) { if(source == 2 || source == 3) return true; if(source < 2 || source % 2 == 0) return false; BigInteger d = source - 1; int s = 0; while(d % 2 == 0) { d /= 2; s += 1; } // There is no built-in method for generating random BigInteger values. // Instead, random BigIntegers are constructed from randomly generated // byte arrays of the same length as the source. RandomNumberGenerator rng = RandomNumberGenerator.Create(); byte[] bytes = new byte[source.ToByteArray().LongLength]; BigInteger a; for(int i = 0; i < certainty; i++) { do { // This may raise an exception in Mono 2.10.8 and earlier. // http://bugzilla.xamarin.com/show_bug.cgi?id=2761 rng.GetBytes(bytes); a = new BigInteger(bytes); } while(a < 2 || a >= source - 2); BigInteger x = BigInteger.ModPow(a, d, source); if(x == 1 || x == source - 1) continue; for(int r = 1; r < s; r++) { x = BigInteger.ModPow(x, 2, source); if(x == 1) return false; if(x == source - 1) break; } if(x != source - 1) return false; } return true; } }


Prueba este código

bool isPrimeNubmer(int n) { if (n == 2 || n == 3) //2, 3 are prime numbers return true; else if (n % 2 == 0) //even numbers are not prime numbers return false; else { int j = 3; int k = (n + 1) / 2 ; while (j <= k) { if (n % j == 0) return false; j = j + 2; } return true; } }


Solo un código de fila:

private static bool primeNumberTest(int i) { return i > 3 ? ( (Enumerable.Range(2, (i / 2) + 1).Where(x => (i % x == 0))).Count() > 0 ? false : true ) : i == 2 || i == 3 ? true : false; }


También puede encontrar el rango de números primos hasta el número dado por usuario.

CÓDIGO:

class Program { static void Main(string[] args) { Console.WriteLine("Input a number to find Prime numbers/n"); int inp = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("/n Prime Numbers are:/n------------------------------"); int count = 0; for (int i = 1; i <= inp; i++) { for (int j = 2; j < i; j++) // j=2 because if we divide any number with 1 the remaider will always 0, so skip this step to minimize time duration. { if (i % j != 0) { count += 1; } } if (count == (i - 2)) { Console.Write(i + "/t"); } count = 0; } Console.ReadKey(); } }


También puedes probar esto:

bool isPrime(int number) { return (Enumerable.Range(1, number).Count(x => number % x == 0) == 2); }


Usando la rutina Soner, pero Math.Ceiling(Math.Sqrt(number)) hasta que sea igual a Math.Ceiling(Math.Sqrt(number)) ese es el truco para la solución ingenua:

boolean isPrime(int number) { if (number == 1) return false; if (number == 2) return true; for (int i = 2; i <= Math.Ceiling(Math.Sqrt(number)); ++i) { if (number % i == 0) return false; } return true; }


bool flag = false; for (int n = 1;n < 101;n++) { if (n == 1 || n == 2) { Console.WriteLine("prime"); } else { for (int i = 2; i < n; i++) { if (n % i == 0) { flag = true; break; } } } if (flag) { Console.WriteLine(n+" not prime"); } else { Console.WriteLine(n + " prime"); } flag = false; } Console.ReadLine();


var number; Console.WriteLine("Accept number:"); number = Convert.ToInt32(Console.ReadLine()); if(IsPrime(number)) { Console.WriteLine("It is prime"); } else { Console.WriteLine("It is not prime"); } public static bool IsPrime(int number) { if (number <= 1) return false; if (number == 2) return true; if (number % 2 == 0) return false; var boundary = (int)Math.Floor(Math.Sqrt(number)); for (int i = 3; i <= boundary; i+=2) { if (number % i == 0) return false; } return true; }

Cambié el number / 2 a Math.Sqrt(number) porque en wikipedia , dijeron:

Esta rutina consiste en dividir n por cada número entero m que sea mayor que 1 y menor o igual que la raíz cuadrada de n . Si el resultado de cualquiera de estas divisiones es un número entero, entonces n no es un primo, de lo contrario es un primo. De hecho, si n = a * b es compuesto (con ayb ≠ 1), entonces uno de los factores aob es necesariamente la raíz cuadrada máxima de n