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;
}
Related
While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
prime = prime;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Here is an example of the program being run.
Program example
The smallest number here should be 8, and the issue is that it begins at 0. The same thing with the largest number.
Program example #2
Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to break out of the loop or change the structure of your code.
I have written the bulk majority of the program, I'm just having trouble debugging it. Something must be wrong with my computation of the prime numbers. For anything I try, it says there are 0 prime numbers. Any help would be greatly appreciated. Code and output are below.
Note: For this program, I am not allowed to use vectors or arrays.
#include <iostream>
#include <cmath>
using namespace std;
// FUNCTION PROTOTYPE FOR read_range
void read_range(int &lower, int &upper);
// FUNCTION PROTOTYPE FOR is_prime
bool is_prime(const int num);
// FUNCTION PROTOTYPE FOR display_primes
void display_primes(const string &prime, const int lower, const int upper);
// DO NOT MODIFY THE MAIN ROUTINE IN ANY WAY
int main()
{
int imin(0), imax(0);
// Read in range
read_range(imin, imax);
// Print prime numbers
cout << endl;
display_primes("Primes: ", imin, imax);
return 0;
}
// DEFINE FUNCTION read_range() HERE:
void read_range(int &lower, int &upper){
cout << "Enter minimum and maximum: ";
cin >> lower >> upper;
while (lower < 2 || upper < 2 || lower > upper){
if (lower < 2 || upper < 2) {
cout << "Error. Minimum and maximum must be at least 2." << endl; }
else if (lower > upper) {
cout << "Error. Minimum must be less than maximum." << endl; }
cout << "Enter minimum and maximum: ";
cin >> lower >> upper; }}
// DEFINE FUNCTION is_prime() HERE:
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0; } // Is not prime
else {
return 1; }}} // Is prime
// DEFINE FUNCTION display_primes() HERE:
void display_primes(const string &prime, const int lower, const int upper) {
int count = 0;
int commaCheck = 0;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
count = count + 1; }}
if (count == 1) {
cout << "There is " << count << " prime number in this range." << endl; }
else {
cout << "There are " << count << " prime numbers in this range." << endl; }
if (count != 0) {
cout << prime;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
if (count == 1) {
cout << i;}
else {
commaCheck = commaCheck + 1; }
if (commaCheck != count) {
cout << i << ","; }
else {
cout << i; }}}
cout << endl; }
else {
cout << "No primes to display." << endl; }}
Output (with input of 2,3)
Enter minimum and maximum:
There are 0 prime numbers in this range.
No primes to display.
is_prime has two issues.
If sqrt(num) is less than 2 the loop never executes and your function has undefined behaviour as it ends without returning (your compiler probably should have warned you about this issue)
If the number is not even then in the first iteration of the loop you call return 1 which means all odd numbers will be labelled as prime.
Changing your loop to this will work (if not be very efficient, there are much better algorithms for finding prime numbers):
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
This is one of the default algorithms for checking how many numbers between two intervals are prime numbers, there are many alternatives, but this is what i prefer and is short and easy to remember
#include <iostream>
using namespace std;
int main(){
int i1min, i1max;
int i, j, k = 0;
bool primeTest;
cin >> i1min;
cin >> i1max;
for(i=i1min; i<=i1max; i++) {
primeTest = false;
for (j=2; j<=i/2; j++) {
if (i % j == 0) {
primeTest = true;
break;
}
}
if (primeTest == false)
k++;
}
cout << k;
return 0;
}
#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;
}
}
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();
}