Respuesta :
Answer:
The attached file is a C program that does much of what you want. It does not output the the sum of the primes, but lists the primes. The output is simple enough to change. This program builds quite easily with GCC.
I don't know what language you're using, so I'm just providing a piece of code I've written that might help you out.
Also:
There are a few tricks in searching for prime numbers. Here are some that I always like to take into account.
1) With the exception of 2 and 3, all primes are one away from a multiple of six
2) When testing a number for divisibility, you only have to test up as far as its square root.
3) You don't need to test for divisibility by composite numbers. Only prime factors are needed. Any composite numbers smaller than x will be multiples of primes smaller than x.
So you can very rapidly find primes with a loop that starts at 6, and goes up to whatever limit you want, incrementing by 6. Let's call the number of that loop x. You then only have to test if the x - 1 is prime and if x + 1 is prime. That eliminates 2/3 of the iterations needed. Also, when you find primes, put them in an array. I would start by creating an array with the numbers 2 and 3 already in it (those being the only two primes that are not adjacent to a multiple of six). Then each number tested only needs to be checked for divisibility by numbers in that array that are less than or equal to the square root of the number being tested. If the number is composite, then it is only divisible by something larger than its square root if it is also divisible by something smaller than its square root.
With all of this big blurb written, and some hard-to-read C code attached, if you're just looking to write something quick to do your homework, and don't care about it being efficient, you can just do something like this javascript style example:
var n, tally = 0, list = [], isPrime;
for(n = 2; n < 100; n++){
isPrime = 1;
for(m = 0; m < list.length && list[m] <= Math.sqrt(n) && isPrime; m++){
if(n % list[m] == 0) isPrime = 0;
}
if(isPrime){
list[list.length] = n;
tally += n;
}
}
console.log('sum of primes: ' + tally);
I haven't run that code, so do watch out for any errors I missed. Good luck!