Saturday, July 25, 2009

How do you find the primes from 1 to 100 using loops in C#?

I wrote and tested the below code in C#. I might point out if you want to make it more efficient, on the line of the j loop, instead of iterating to i-1, you could iterate to i/2 as it is impossible for any number to be divisible by a number more than half of it. However saying that since you are only looking for 1- 100 , this is fast enough... you should get the results in around 1 second.





int objStartVal = 1;


int objEndVal = 100;


int i, j;


for ( i=objStartVal; i%26lt;=objEndVal; i++ )


{


Boolean isPrime = true;


for (j=1;j%26lt;=i-1;j++)


{


if (j!=1)


{


if ((i % j) == 0)


{


isPrime = false;


}


}


}


if (isPrime)


{


MessageBox.Show(i + " is a prime number.");


}


}

How do you find the primes from 1 to 100 using loops in C#?
Well, not that it is that difficult, but it is more efficient to just use a hash table if you only need such a small group of prime numbers. There are only 26 numbers less than 100 that are prime (including 1).





If you're looking for an algorithm that will work for you, I suggest looking online or through just about any C programming book. Prime number finders are pretty common. My buddy writes them in different assembly languages he learns just because it's a simple little problem to solve.





But, if you just want the answer, here is a simple algorithm, and below is the link to learn more abou it:





ArrayList primeNumbers = new ArrayList();





for(int i = 2; i %26lt; 100; i++)


{


bool divisible = false;





foreach(int number in primeNumbers)


if(i % number == 0)


divisible = true;





if(divisible == false)


primeNumbers.Add(i);


}
Reply:I won't write the code for you as it sounds like a homework question, but here's the basic algorythm (skip 1, 2, 3 since you know they're prime):





(inside the loop) :


Divide the number by every number between 1 and itself, looking for a remainder each time. If once comes back with no remainder, it's not prime
Reply:i dunno in c#, but here it is in c++, convert it or something :p





#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


using namespace std;





int main()


{


int number, variable, display_num;





for (number = 3; number %26lt; 100; number++)


for (variable = 2; (number%variable %26gt; 0) %26amp;%26amp; variable %26lt; (number); variable++)


for (display_num = 0; ((number - variable) == 1) %26amp;%26amp; (display_num == 0); display_num++)


cout %26lt;%26lt; setw(5) %26lt;%26lt; number %26lt;%26lt; setw(5);


cout %26lt;%26lt; endl;





system("pause");


return 0;


}








sorry i don't know c#, i did this as an assignment a long time ago for c++, should be similar to what you are trying to get too. obviously this was a beginning course, i kinda of laughed at the code now that i see it, but it worked.



poems

No comments:

Post a Comment