How do you find the primes from 1 to 100 using loops in C#?
- Abraham AlexLv 41 decade agoFavorite Answer
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<=objEndVal; i++ )
Boolean isPrime = true;
if ((i % j) == 0)
isPrime = false;
MessageBox.Show(i + " is a prime number.");
- 1 decade ago
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 < 100; i++)
bool divisible = false;
foreach(int number in primeNumbers)
if(i % number == 0)
divisible = true;
if(divisible == false)
- 1 decade ago
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
- No NameLv 41 decade ago
i dunno in c#, but here it is in c++, convert it or something :p
using namespace std;
int number, variable, display_num;
for (number = 3; number < 100; number++)
for (variable = 2; (number%variable > 0) && variable < (number); variable++)
for (display_num = 0; ((number - variable) == 1) && (display_num == 0); display_num++)
cout << setw(5) << number << setw(5);
cout << endl;
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.