0

I am needing help figuring out how to get this program to function correctly. The program is developed in order for a user to type in any number and it will tell if the number is prime or not. This works, however, I cannot figure out how to get it to say 2 is prime, and 9 is not prime. It also says 49 is prime and it is not. If anyone could help me with this I would greatly appreciate it!

//This program uses a function that returns true or false.
#include <iostream> 
using namespace std; 

//Function prototype
bool isPrime (int); 

int main()
{
	int val; //Get a number from the user.
	cout<<"Enter a positive number and I will tell you ";
	cout<<"if is a prime number or not: ";
	cin>>val;  //Indicate whether it is prime or not.
	if (isPrime(val))
	cout<<val<<" is a prime number.\n";
	else 
	cout<<val<<" is not a prime number.\n";
	return 0;
} //**********************************************************
  //Definition of function isPrime. This function accepts an *
  //integer arguement and tests it to be prime or not. The   *
  //function true if the arguement is prime or false if the  *
  //arguement is not. The return value is a bool.            *
  //********************************************************** 
bool isPrime 
	(int number)

{
	bool status;
	{
		int input = 2;
		double root = sqrt((double)(number));
		if(number%input==0) 
			return false;
		input++;while(input<root)
		{
			if(number%input==0) 
				return false;input+=input+2;
		}return true; 
	}
	return status;
}
3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by caut_baia
0

what happens if you change line 32 to

double root = sqrt(double(number)) + 1;

[EDIT]
I think you might also want to recheck the way you are incrementing your test variable.

Edited by NathanOliver: n/a

-2
#include <iostream>

int main ()  {
   int num;
   bool prm;
   const char* na[]={"prime","not prime"};
   std::cin >> num;
   for (int x=2;x<=10;x++)  {
      if (prm=!(num%x)&num!=x) break;         
    }
   std::cout << na[prm];
 }

Edited by Dani: Fixed formatting

Votes + Comments
poor coding
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.