Diferencia entre revisiones de «Implementación de algoritmos de teoría de números/Criba de Eratóstenes»

Contenido eliminado Contenido añadido
Raulshc (discusión | contribs.)
Sin resumen de edición
Línea 129:
 
exit 0
</source>
 
== En C# ==
 
<source lang="csharp">
// Iker Ruiz Arnauda - 2012
// Sieve of Eratosthenes - C#
// Criba de Eratóstenes
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
 
namespace Main
{
class Program
{
static void Main(String[] Args)
{
Boolean ended = false;
do
{
Console.WriteLine("Type the upper limit (Positive Intiger):");
try
{
//Read size of the array from the user, convert it to an Intiger.
var SuperiorLimit = Convert.ToInt32(Console.ReadLine());
 
//Create the array.
Boolean[] primesArray = new Boolean[SuperiorLimit];
//Fill the boolean array, set all false by default.
for (Int32 i = 2; i < SuperiorLimit; i++)
primesArray[i] = false;
 
for (Int32 i = 2; i * i < SuperiorLimit; i++)
{
if (!primesArray[i])
{
for (Int32 k = 2; i * k < SuperiorLimit; k++)
{
//Found prime, set the value truth.
primesArray[(i * k)] = true;
}
}
}
 
//Print Results
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Found Primes:");
Console.ForegroundColor = ConsoleColor.Green;
for (int j = 2; j < primesArray.Length; j++)
{
if (!primesArray[j])
Console.WriteLine("[" + j + "] ");
}
 
//Operation completed succesfully, we kill the loop.*/
ended = true;
Console.Read();
}
//If the operation fail, show the error to the user and let him try again.
catch (Exception ex)
{
Console.WriteLine("[ERROR] " + ex.Message);
Console.WriteLine("Press enter to try again...");
Console.ReadLine();
Console.Clear();
}
} while (!ended);
}
}
}
</source>