Prime Number Improvements, Moved the methods into a unique class. The list has been exchanged for a single string with line breaks. This is much more efficient and doesnt require the foreach loop to output the data. Can just output the single string.

This commit is contained in:
lukejelse04 2021-05-25 20:31:16 +01:00
parent 95c5fe0e23
commit 1168d0b934
3 changed files with 46 additions and 29 deletions

View File

@ -43,6 +43,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="prime.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

View File

@ -10,36 +10,9 @@ namespace Prime_Numbers__Efficient_
{
static void Main(string[] args)
{
int startNum = 2;
int maxNum = Convert.ToInt32(Console.ReadLine());
bool isPrime = true;
List<int> primeList = new List<int>();
prime primeFinder = new prime();
for (int x = startNum; x <= maxNum; x++)
{
for (int y = 2; y < (x / 2) + 1; y++)
{
if ((x % y == 0))
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
primeList.Add(x);
}
else
{
isPrime = true;
}
}
foreach (var item in primeList)
{
Console.WriteLine(item);
}
Console.WriteLine(primeFinder.getPrimes(2, 2000000));
Console.ReadLine();

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prime_Numbers__Efficient_
{
class prime
{
//Prime until proven not prime
private bool IsPrime { get; set; } = true;
private string Primes { get; set; }
public string getPrimes(int startNum, int endNum)
{
for (int x = startNum; x <= endNum; x++)
{
for (int y = 2; y < (x / 2) + 1; y++)
{
if ((x % y == 0))
{
IsPrime = false;
break;
}
}
if (IsPrime == true)
{
Primes += x + "\n";
}
else
{
IsPrime = true;
}
}
return Primes;
}
}
}