Reputation: 13
My program takes a user input, int n
, and prints out the first n
amount of prime numbers. This is working as intended
eg. if user inputs 8
as n. the program will print :
2 3 5 7 11 13 17 19
My problem is adding the function isPrime(n)
(which is not allowed to be changed)
here is what i've tried but im just getting the output :
2 3 5 7 11 13 17 19 0 is not a prime number,
when it should read 2 3 5 7 11 13 17 19 8
is not a prime number
#include "prime.h"
#include <iostream>
int main()
{
int n;
std::cout << "Enter a natural number: ";
std::cin >> n;
for (int i = 2; n > 0; ++i)
{
bool Prime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
Prime = false;
break;
}
}
if (Prime)
{
--n;
std::cout << i << " ";
}
}
if (isPrime(n))
{
std::cout << n << " is a prime number." << std::endl;
}
else
{
std::cout << n << " is not a prime number." << std::endl;
}
system("pause");
}
prime.h :
#ifndef PRIME_H_RBH300111
#define PRIME_H_RBH300111
bool isPrime(int);
#endif
#pragma once
the definition of isPrime(int)
prime.cpp :
#include <cmath>
#include "prime.h"
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
else if (n == 2)
{
return true;
}
else if ((n % 2) == 0)
{
return false;
}
}
I cannot alter the .h
file of prime.cpp
I just need the isPrime(n)
function to work on the main()
function code
the user input n, does not seem to be taking the number 8
. but instead 0
giving me the output. 0
is not a prime number
rather than : n (8)
is not a prime number
Upvotes: 1
Views: 167
Reputation: 1
You are decrementing n in the for loop. The for loop has the condition 'n > 0', so you know n isn't > 0 when the loop finishes. You could either save the value of n in a different variable (i.e. "int nOrig = n;") and use that for the prime test, or use a different variable in the loop.
Upvotes: 0
Reputation: 206567
You are decrementing n
in the loop. At the time the loop exits, the value of n
is 0
.
You can solve the problem by:
n
and resetting the value of n
after the loop exits.Here's the second method:
int copyN = n;
for (int i = 2; n > 0; ++i)
{
...
}
n = copyN;
if (isPrime(n))
...
Upvotes: 1