Our first problem was to ask the user how many prime numbers he/she would like, then to find and output that many. We both (eventually) got it to work. Here was my code:
// "Primes" (2009) - J. Sias #include "stdafx.h" #include "iostream.h" // for cin and cout #include "math.h" // for sqrt function using namespace std; bool isPrime(int); // returns true if prime, false if not int main(void) { int primesWanted, primesFound = 0, nextInt = 2; char toEnd; // ask how many primes wanted cout << "How many primes do you want? (minimum 1): "; cin >> primesWanted; // find and display that many primes do { if(isPrime(nextInt)) { cout << nextInt << " "; primesFound++; } nextInt++; } while (primesFound < primesWanted); // pause so user can see output cout << "\n" << "There you go! Enter a character to continue... "; cin >> toEnd; return(0); } bool isPrime(int num) { // 2 is prime by definition if(num == 2) return true; // test for factors for(int i = 2; i <= (int) sqrt((float) num); i++) if(num % i == 0) return false; // if no factors, it's prime return true; }
His code was a lot different, but both worked just as well, which goes to show there are as many solutions to a given problem as there are programmers!
Now that I've got Visual Studio set up and (sort of) figured out the actual IDE itself, which is a bit cumbersome, I hope the next program will go more smoothly. Fun!
4 comments:
Looks like Greek to me, but sounds fun ;)
Greek, good one :)
It is Greek, how did you know? er... maybe it's geek.
Haha, Geek for sure! But I think Kat likes Geek and Greek, since she's a biologist and born and raised in Greece. :-)
Post a Comment