Hey, this is my first post around here!
I've been playing with c++ programming for the last couple weeks and thought joining a forum would be helpful in learning more about c++
Anyway, i'm here bacause i've been working on a program that would display only prime numbers within a interval given by the user.
I was kind of proud of myself when I finally got one that worked! lol
Problem is, i can't figure out a way to include 2,3,5,7 in it...
I tried doing a if statement such as
if((a%x)!=0) cout<< a<<endl;
and adding a for (x=2; x=7; x++){
it kind of makes sense that it would work, but i don't know why it doesn't!
I know is probably a silly mistake somewhere, but what is it?? haha, it's driving me crazy
this is my code pasted:
#include <iostream>
using namespace std;
void function ();
int m, a;
int main(){
while (true){
system ("CLS");
cin.clear();
cout<<"FINDING PRIME NUMBERS WITHIN A RANGE"<<endl<<endl;
cout<<"Enter range"<<endl<<endl;
cout<<"From one to:";
cin>> m;
cout<<endl;
function ();
system ("PAUSE");
}
return 0;
}
void function (){
cout<<"2"<<endl<<"3"<<endl<<"5"<<endl<<"7"<<endl; //This is the part I cheated.
for ( a=1; a<=m; a++ ){
int d=2;
int t=3;
int f=5;
int s=7;
if ((a%d)!=0 && (a%t)!=0 && (a%f)!=0 && (a%s)!=0 && a!=1) cout<< a<< endl;
}
}
That person takes a number and moduluses it by all of the numbers greater than 1 and less than itself. If the two numbers tested come out to be an even divide (the modulus of the two numbers equals zero) then the number is not prime.
First you should think about what makes a number prime: it can only be divided evenly by 1 and itself.
Remember you can divide it by all the numbers from 2 to the square root of the number: any number greater than that can not be a factor of the number chosen.
The way I wrote my prime number program was by making an "is_prime" boolean. This is set to true as a default.
I then loop a variable from 2 until it is < the square root of the number.
Each cycle, the given number is divided by the variable: if it has no remainder, the loop is broken, the boolean is set to false, and it goes to the results:
It then displays "Your number is False" or "Your number is True" depending on what the boolean is set to :-).
I hope this helps.