I've been learning C++ for few weeks, however, I got stuck, I have a function isPrime(), works great to show if the number is prime or no, I need to display all the Prime numbers which are less than 200. But it's not working see line marked with comment
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
if (isPrime(Num))
{
cout << " is a Prime number." << endl;
}
else
cout << " is not a Prime number." << endl;
return 0;
}
//isPrime
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else if
for(int n = 2; n < 200; n++) { // HERE
// isPrime will be true for prime numbers
isPrime = isPrimeNumber(n);
if(isPrime == true)
cout<<n<<" ";
}
return 0;
else
return false;
}
}
}
return false;
}
You added the loop in the wrong place. That function is only for checking a particular number. Either you would need to make another function to print all the prime numbers which are less than 200 or you can directly add the loop in the main() function, like i did.
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
// Check numbers here
for(int n = 2; n < 200; n++) {
if (isPrime(n)){
cout << n << " is a Prime number." << endl;
}
}
return 0;
}
//isPrime - This is your original isPrime Code
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else
return false;
}
}
}
return false;
}
#include <iostream>
using namespace std;
int main()
{
char ch;
int n;
do {
cout << "Enter a number:";
cin >> n;
if (n % 2 == 0)
cout << "The number is even.\n";
else
cout << "The number is odd.\n";
bool prime;
for (int i = 2; i < n; ++i) {
if (n % i == 0)
prime = true;
}
if (prime) {
cout << "The number is not prime.";
}
else
cout << "The number is prime.";
cout << "Do you want to continue?[y/n]";
cin >> ch;
} while (ch == 'y' || ch == 'Y');
}
If the loop enters once into if(prime) then it never goes in the else.
On first run of loop if 3 is entered, it outputs prime. Then in next if 4 if entered it show not prime but after that whenever any prime number is entered it shows not prime.
first of all your
bool prime;
is not initialized. Second it should be initialized inside do while() loop and it is better to move that variable declaration there:
bool prime = false; // move it here and initialize
for (i = 2; i < n; ++i) {
if (n % i == 0)
prime = true;
}
and you use boolean flag in reverse, which makes your program unreadable, you better fix that:
bool prime = true; // move it here and initialize
for (i = 2; i < n and prime; ++i) {
if (n % i == 0)
prime = false;
}
if (prime)
cout << "The number is prime.";
else
cout << "The number is not prime.";
I am suppose to make a program that asks a user to input an integer 'n' between 1 and 100, and have an input validation loop. The program will then calculate the first 'n' prime numbers and print them. So I figured out how to calculate the prime numbers and display them, 10 numbers per line, all in the main function. What I have to do is to have a function called isPrime() that takes an integer and returns true if it is prime and false otherwise. I'm not sure how to go about this. This is the code I have for function main().
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
int count = 0;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
while (number < 0 || number > 100)
{
cout << "Invalid number." << endl;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
}
cout << "The first " << number << " primes: \n" << endl;
for (int i = 2; number > 0; ++i)
{
bool isPrime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}
cout << endl;
system("pause");
return 0;
}
Any help is good, thanks in advance.
You seem to be testing i % j for every j lower then i. But if you tested for j = 3 then you can exclude all multiples of 3. When a number can't be divided by 3 it can't be divided by 6. This will improve performance.
You can also implement the AKS primalty test https://en.wikipedia.org/wiki/AKS_primality_test
This might be a little more work. I don't know the details of this test but it is deterministic and works on all numbers.
If you want a function bool isPrime(int number) you can just extract this code from your main method, it looks something like this:
bool isPrime(int number){
for (int j = 2; j < number/2; ++j)
{
if (number % j == 0)
{
return false;
}
}
return true;
}
The for loop in the main function will be something like:
for (int i = 2; number > 0; ++i)
{
if (isPrime(i))
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}
thanks to your help last night I was able to get my program computing my input properly, but now I am have trouble formatting my output properly. This is the problem:
My program should only print "is prime" on lines with prime numbers. But it prints on ever line like this:
http://oi42.tinypic.com/30igbvq.jpg
I cannot for the life of me figure out why it is doing this, all of my functions should work.
Stack I need your help again!
#include <iostream>
using namespace std;
void primecheck(int x); // proto
void countr(int rnm, int lnm); // proto
void prime(int x) // this function finds the prime factors of a number.
{
int lastr = 2;
int count = 0;
while (lastr < x)
{
if (x % lastr == 0)
{
cout << x << " " << lastr << "*";
x /= lastr;
}
else
++lastr;
}
primecheck(x); // calls to check if number is prime, "Is prime"
}
void console(int rnum, int lnum) // this prompts the user for two numbers then stores the answers
{
cout << "please enter two numbers ";
cin >> rnum;
cin >> lnum;
countr(rnum, lnum);
}
void countr(int rnm, int lnm) // this function loops the prime function until all the numbers are computed
{
int i = rnm;
do{
prime(i);
i++;
} while (i <= lnm);
return;
}
int main() // main, calls console then pauses when finished
{
int e = 0;
int r = 0;
console(e, r);
system("PAUSE");
}
void primecheck(int x) // checks to see if then number is prime. if counter is equal to 2 than number is prime.
{
int counting = 0;
for (int a = 1; a <= x; a++)
{
if (x %a == 0)
{
counting++;
}
}
if (counting == 2)
{
cout << x << " is prime " << endl;
}
else
{
cout << x << endl;
}
}
You're using a /= operator in prime(). That's an assignment operator and is modifying the value of x, making x always prime whenever primecheck() is called.
I am trying to make a program that determines if the number is prime or composite. I have gotten thus far. Could you give me any ideas so that it will work? All primes will , however, because composites have values that are both r>0 and r==0, they will always be classified as prime. How can I fix this?
int main()
{
int pNumber, limit, x, r;
limit = 2;
x = 2;
cout << "Please enter any positive integer: " ;
cin >> pNumber;
if (pNumber < 0)
{
cout << "Invalid. Negative Number. " << endl;
return 0;
}
else if (pNumber == 0)
{
cout << "Invalid. Zero has an infinite number of divisors, and therefore neither composite nor prime." << endl;
return 0;
}
else if (pNumber == 1)
{
cout << "Valid. However, one is neither prime nor composite" << endl;
return 0;
}
else
{
while (limit < pNumber)
{
r = pNumber % x;
x++;
limit++;
if (r > 0)
cout << "Your number is prime" << endl;
else
{
cout << "Your number is composite" << endl;
return 0;
}
}
}
return 0;
}
Check out http://en.wikipedia.org/wiki/Prime_number and http://en.wikipedia.org/wiki/Primality_test
The simplest primality test is as
follows: Given an input number n,
check whether any integer m from 2 to
n − 1 divides n. If n is divisible by
any m then n is composite, otherwise
it is prime.
#include <iostream>
#include <math.h>
// Checks primality of a given integer
bool IsPrime(int n)
{
if (n == 2) return true;
bool result = true;
int i = 2;
double sq = ceil(sqrt(double(n)));
for (; i <= sq; ++i)
{
if (n % i == 0)
result = false;
}
return result;
}
int main()
{
std::cout << "NUMBER" << "\t" << "PRIME" << std::endl;
for (unsigned int i = 2; i <= 20; ++i)
std::cout << i << "\t" << (IsPrime(i)?"YES":"NO") << std::endl;
std::cin.get();
return 0;
}
bool check_prime(unsigned val) {
if (val == 2)
return true;
// otherwise, if it's even, it's not prime.
if ((val & 1) == 0)
return false;
// it's not even -- only check for odd divisors.
for (int i=3; i*i<=val; i+=2)
if (val % i == 0)
return false;
return true;
}
with respect ur code u didn't check if i enter 2 what will be happened,
and also u didn't return any thing if it is prime....thats why it is always returning prime in spite the number is composite .
here is the code below =>
#include<iostream>
using namespace std;
int main(){
int pNumber, limit, x, r;
limit = 2;
x = 2;
cout << "Please enter any positive integer: " ;
cin >> pNumber;
if (pNumber < 0){
cout << "Invalid. Negative Number. " << endl;
return 0;
}
else if (pNumber == 0){
cout << "Invalid. Zero has an infinite number of divisors, and therefore neither composite nor prime." << endl;
return 0;
}
else if (pNumber == 1){
cout << "Valid. However, one is neither prime nor composite" << endl;
return 0;
}
else if (pNumber == 2){
cout << " Your number is prime" << endl;
return 0;
}
else{
while (limit < pNumber){
r = pNumber % x;
x++;
limit++;
if (r > 0){
cout << "Your number is prime" << endl;
return 0;
}
else{
cout << "Your number is composite" << endl;
return 0;
}
}
}
return 0;
}
For one thing, you'll want to break out of your loop when you find some x where pNumber % x == 0. All you need to do is find one factor of pNumber greater than 1 and less than pNumber to prove it's not prime -- no point in searching further. If you get all the way to x = pNumber without finding one, then you know pNumber is prime. Actually, even if you get to the square root of pNumber without finding one, it's prime, since if it has a factor greater than that, it should have a factor less than that. Make sense?
I don't know what you have been taught thus far, but my discrete mathematics teacher was a fan of the Miller-Rabin test. It is a pretty accurate test that is very easy to code, within a few base tests you have a very negligible chance that you have a Carmichael Number. If you haven't gotten that far in your studies I would just stick to some basic division rules for numbers.
Simplest method is for a given number n , if it is perfectly divisible with any number between 2 to sqrt(n), its a composite, or else its prime
Hi i have done this that also without using math.h header file....Have used turboc compiler.
Following program checks whether the number is prime or composite.
#include<iostream.h>
#include<conio.h>
class prime
{
int a;
public:
void check();
};
void prime::check()
{
cout<<"Insert a number";
cin>>a;
int count=0;
for(int i=a;i>=1;i--)
{
if(a%i==0)
{
count++;
}
}
if(count==1)
{
cout<<"\nOne is neither prime nor composite";
}
if(count>2)
{
cout<<"\nThe number is composite " ;
}
if(count==2)
{
cout<<"\nThe numner is prime";
}
}
void main()
{
clrscr();
prime k;
k.check();
getch();
}