Getting First 100 Prime numbers
getprimes(500);
private void getprimes(int mysize)
{
int[] values = new int[mysize];
int counter = 0;
int jjj = 0;
for (int i = 2; counter < mysize; i++)
{
if (checkprime(i, ref jjj))
{
values[counter] = i;
counter++;
}
}
// Just to Display
string answer = "";
string smallanswer = "";
for (counter = 0; counter < mysize; counter++)
{
smallanswer += values[counter].ToString() + "-";
if (smallanswer.Length > 200)
{
answer += smallanswer + "\r\n";
smallanswer = "";
}
}
MessageBox.Show(answer + smallanswer + "--" + jjj.ToString());
}
private bool checkprime(int x,ref int jjj)
{
for (int i = 2; i <= (Math.Sqrt(x) ); i++)
{
if (((x / i) * i) == x) return false;
jjj++;
}
return true;
}
Any better algorithm?
//call getprimes2() from client
getprimes2() from client
//Have a global variable
int[] MyPrimes;
private void getprimes2(int mysize)
{
MyPrimes = new int[mysize];
MyPrimes[0] = 2;
int counter = 1;
int jjj = 0;
for (int i = 2; counter < mysize; i++)
{
if (checkprime2(i, counter))
{
MyPrimes[counter++] = i;
}
}
string answer = "";
string smallanswer = "";
for (counter = 0; counter < mysize; counter++)
{
smallanswer += MyPrimes[counter].ToString() + "-";
if (smallanswer.Length > 200)
{
answer += smallanswer + "\r\n";
smallanswer = "";
}
}
MessageBox.Show(answer + smallanswer + "--" + jjj.ToString());
}
private bool checkprime2(int x, int counter)
{
for (int i = 0; i < counter ; i++)
{
if (((x / MyPrimes[i]) * MyPrimes[i]) == x) return false;
}
return true;
}
/// <summary>
/// Find top x prime numbers.
/// </summary>
/// <param name="x">Integer, Top[] specifier</param>
/// <returns>An Arraylist containing top x prime numbers</returns>
public static ArrayList FindPrimes(int x)
{
System.DateTime startTime = System.DateTime.Now;
if(x<=0)
{
return null;
}
Console.WriteLine("Top " + x + " Prime numbers are: ");
ArrayList answer = new ArrayList();
answer.Add(2);
for (int i = 3; ; i++)
{
bool divisible = false;
foreach (int y in answer)
{
if (i % y == 0)
{
if( divisible = true||i<2*y)
break;
}
}
if (divisible)
{
}
else if (divisible == false && answer.Count < x)
{
answer.Add(i);
Console.WriteLine(i);
}
else break;
}
System.DateTime endTime = System.DateTime.Now;
Console.WriteLine("Duration to find top[ "+x+"] Prime numbers is"+(endTime-startTime).ToString());
return answer;
}
private bool checkprime2(int x, int counter)
we can use best of both.
1) scan the previous primenumbers for divisability check
2) where in these numbers are less than square root of the number that is being verified.