Sunday, August 2, 2009

C++ Programming HELP?

I have no idea of where to start on this assignment:


Write a program that displays all the prime numbers between 50 and 100.


A prime number divides only in 1 and in itself.


Note: You can make it more efficient by checking the divisors of N from 2 and upto


square root(N), instead of (N)).


There is a library function called sqrt(n) which is included in the %26lt;math.h%26gt; header file.


sqrt(n) returns the square root of n.


File name: prime.c





please help me, totally lost here

C++ Programming HELP?
wow that's a tuffie
Reply:seems easy try this.


start checking every number to see wether it is prime or not!(you need a for struct)


for checking if a number is prime or not you need for that checks (your number)mod (another number from 2 to sqrt(your number))


if it is 0 you will write count++


and at the end if count is=0 print the number!


if it needs more explanation let me know
Reply:for(int i = 50; i %26lt; 101; i++)


{


for(int j = 0; j %26lt; Math.sqrt(i); j++)


{


if(i/j != 0)


{


printf("%d", i);


}


}


}





at least that's the general idea...
Reply:#include %26lt;iostream%26gt;





using namespace std;





void main()


{


cout%26lt;%26lt; "53 59 61 67 71 73 79 83 89 97 " %26lt;%26lt; endl;


}
Reply:OK. Let n be the number you're testing to see if it's a prime. This will start at 50 and increase to 100.





Function to test if n is a prime:


Let f be some number that you think may be a factor of n (start with f = 2), and let g = 1.


If (n % f) == 0, then n is a multiple of f and therefore not prime, so return false.


Otherwise: let f += g.


If f == 3 then let g = 2.


If f %26gt; 5 then let g = 6 - g.


If f * f %26gt; n, then f is bigger than the square root of n, meaning n must be prime so return true. Otherwise, test (n % f) again.





Note: you don't actually need to evaluate the square root at all. Doing an integer multiplication on each iteration is still quicker, on average, than evaluating a square root once! This is because most numbers are not prime, so you will usually drop out of the loop before doing this multiplication too many times. The reason for alternately adding 2 or 4 (which is what g does) is so you skip over all odd multiples of 3, which are not prime and so needn't be tested as potential factors (since their factors have already been tested). So the sequence goes 2 (miss 1) 3 (miss 2) 5 (miss 2) 7 (miss 4) 11 (miss 2) 13 (miss 4) 17 %26amp;c.





Note also: You could do the "alternately adding either 2 or 4" thing with n, and it would be a little more efficient since you are eliminating all multiples of 2 and 3 (though these will get rejected in 1 or 2 iterations anyway). But 50 doesn't fit this sequence, and starting with 53 would be cheating.


No comments:

Post a Comment