![]() |
|
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Newbie
Join Date: Aug 2005
Posts: 22
Rep Power: 0
![]() |
Prime Numbers
This exercise took me donkey's years to do (I am quite new to this). I have a solution, but for some reason, '1' isn't picked up as a prime number.
The exercise is this (taken from Bruce Eckel's guide, chapter 3) 2. Write a program that uses two nested for loops and the modulus operator (%) to detect and print prime numbers. This is my solution, with the numbers 1 - 100 int main(int nNumberofArgs, char* pszArgs[])
{
int number = 0;
for (int i = 0; i <= 100; i++)
{
int modulus = 1;
int primecount = 0;
for (int i = 0; i <= number; i++)
{
double answer = number % modulus;
if (answer == 0)
{
primecount++;
}
modulus++;
}
if (primecount == 2)
{
cout << number << endl;
}
number++;
}
system("PAUSE");
return 0;
}Any tips on how to do this better would be much appreciated, as my code doesn't 'feel' too clean (the variable's and there positions in the program seem wrong). Can it be done with just for loops? Also, is it normal to struggle with these exercises so early on? I am trying to read through the chapters and then attempt the tasks, but occasionally find certain tasks very difficult and time consuming, thus making me frustrated and slowing down the learning process. Is the best way to tackle this guide to work through all the exercises in each chapter? Cheers, |
|
|
|
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|