C# Help


scarface

Member
Joined
Mar 30, 2004
Messages
329
I am trying write some C# code, that finds all the prime numbers between 1-100 and I cannot figure out how to reconize that the numbers are prime. Any help suggestions? I also need to average them afterwards, I have no problem doing that though, and I know what the prime numbers from 1-100 are, but I want the program to do it.

The only thing I have came up with would be to make one method for prime that declares all the prime numbers, and then the main loop that counts from 0 to 100 and check each number for primality.
 
You could use the property that prime numbers can only be divided into an integer by 1 and by themselves.

Here's some pseudo:

CODE

LIST primes;

for(int i = 1; i <= 100; i++) {
boolean isPrime = true;

for(int j = 2; isPrime && j <= (int)sqrt(i); j++) {
if((i % j) == 0) isPrime = false;
}

if(isPrime) primes.add(i);
}
 
If I remember correctly, you will need to do something like this.
for every x from 1 to 100, take squareroot of x; if x is indivisible by all of the primes below the squareroot value of x, then x is prime. If x is prime, store x in an array or something (prime_array) and move along doing the same for all x -> checking everytime if x is divisible by a number in prime_array that is less than sqrt(x).

EDIT: Ah! Beaten with a better answer!
 
Exophase said:
It's best to do this kind of thing with a sieve. This is a simple one:

http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes



Thanks guys for the quick responses. this has been a fun and interesting language to learn so far, and certainly great for my first language!


CODE

// while loop when n <= 100
while (n <= 100)
{
bool isPrime = true;

// test if n is prime
for (x = 2; x < n; x++)
{
if ((n % x) == 0)
{
isPrime = false;
break;
}
}

if (isPrime == true)
{
sumOfPrimes = sumOfPrimes + n;
totalPrimeNumbers++;



is what I came up with so far, and it seems to work. I am interested to learn how to use an array to do this, so I may try another method later.
 
Last edited by a moderator:
Back
Top