prime number program (C++)

November 6, 2010 at 10:10:23
Specs: Windows 7
I am currently learning C++ (beginner level) and my assignment was to build a program that will display all the prime numbers between 1 and 100.
I wrote this algorithm:

#include <iostream>
using namespace std;

int main() {

int x, y, z;

for(x=1; x <= 100; x++) {
for(y=x-1; 0 < y; y--) {

z = x % y;
if(z!=0) cout << x << "\n";
}

}
return 0; }

Which just displays all the numbers between 1 and 100 over and over…
My compiler is Visual Studio 2010.
What can I do to make it work?
Thanks!


See More: prime number program (C++)

Report •

#1
November 7, 2010 at 13:57:46
hi, i tried to write the code but it was harder than i though (at least for me) because i am a beginner too. but i found the code on the net and i understood it so i hope you will like it.

#include <iostream>
using namespace std;

int NUMBER_ENTERD;
bool IS_PRIME = true;


int main()
{
while(true)
{
//intro
cout << "Enter a number: ";
cin >> NUMBER_ENTERD;
cout << "\n........................................ \n";

//prime checker
//first check if the number is greater than 1
if(NUMBER_ENTERD > 1)
{
for(int t=2; t<NUMBER_ENTERD; t++)
{
if(NUMBER_ENTERD % t == 0)
{
IS_PRIME = false;
}
}
}
else
{
IS_PRIME = false;
}


//print the result
if(IS_PRIME == true)
{
cout << "The number " << NUMBER_ENTERD << " is prime\n";
}
else
{
cout << "The number " << NUMBER_ENTERD << " is not prime\n";
}

cout << "........................................ \n\n\n\n";
system("PAUSE");
cout << "\n\n\n";
}
return 0;
}


Report •

#2
November 7, 2010 at 14:06:13
ooooh you know there is something wrong with this code, i will try to fix it help me if you can

Report •

#3
November 7, 2010 at 14:12:09
hey i am sorry about that, but i found the wrong phrase is in the (If else loop )
else
{
IS_PRIME = false;
}


it should be

else
{
IS_PRIME = true;
}

and there just the loop from 1 to 100 i am sure you can write it


Report •

Related Solutions

#4
November 7, 2010 at 15:08:27
nawar youssef: it should be

else
{
IS_PRIME = true;
}

Incorrect.

How To Ask Questions The Smart Way


Report •

#5
November 7, 2010 at 17:15:39
The next thing you need to think about:

Is 1 a prime number?


Report •

#6
November 7, 2010 at 23:03:57
hi Razor2.3 I think you write but can you tell me why either its in math or in programing?? thank you

Report •

Ask Question