473,659 Members | 3,277 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need help with prime numbers program

Write a program that prompts the user to input a positive integer. It
should then output a message indicating whether the number is a prime
number. (Note: An even number is prime if it is 2. An odd integer is
prime if it is not divisible by an odd integer less than or equal to
the square root of the number.) I was given this assignment in my c++
class and I'm having trouble with it. I've looked at the professors lab
solutions but I just dont understand it. This is the code I have.

#include <iostream>
#include <cmath>

using namespace std;
int isprime(int);

int main()
{
int inputnumber;

cout << "Input a positive integer:";
cin >> inputnumber;

if (isprime(inputn umber))
cout << inputnumber << " is prime";
else
cout << inputnumber << " is not prime";
int isprime(int inval);
int retval = 1;
int counter = 2;
int inval;

while ((counter < sqrt(retval)) && retval != 0)
{
if (inval % counter == 0)
retval = 0;
counter++;

return retval;
}

return 0;
}

Im getting an ambigous call to overload on my square root function.
Other than that the program is just not working, can someone please
help me out here?

Nov 9 '05 #1
7 7385
br************@ gmail.com wrote:
Write a program that prompts the user to input a positive integer. It
should then output a message indicating whether the number is a prime
number. (Note: An even number is prime if it is 2. An odd integer is
prime if it is not divisible by an odd integer less than or equal to
the square root of the number.) I was given this assignment in my c++
class and I'm having trouble with it. I've looked at the professors lab
solutions but I just dont understand it. This is the code I have.

#include <iostream>
#include <cmath>

using namespace std;
int isprime(int);

int main()
{
int inputnumber;

cout << "Input a positive integer:";
cin >> inputnumber;

if (isprime(inputn umber))
cout << inputnumber << " is prime";
else
cout << inputnumber << " is not prime";
int isprime(int inval);
1. This is a function declaration since it ends with a semicolon-- you
need a function definition (it was already declared above anyway).
2. You can't define a function within main. You need to close main and
define this function separately (either before or after main).
3. Why return an integer from what is clearly a true/false function?
That is what bool is for.

int retval = 1;
int counter = 2;
I'd give counter a more suggestive name, like divisor. Also since the
candidate divisors are 2,3,5,7,9,..., it would be more efficient to test
for 2 separateley, and then do the odds in the loop so that you can
increment divisor by +2 in each iteration.
int inval;
You don't need to declare a variable which is already passed in to the
function as a named parameter.

while ((counter < sqrt(retval)) && retval != 0)
Look at the first condition-- do you see that it will *never* be true?
Think carefully about what you're comparing (yet more reason to use
clear and descriptive variable names). Also, you need <= not <, but see
my note at the end of this post.
{
if (inval % counter == 0)
As soon as this condition is satisfied you know the number is not prime.
It makes sense to then immediately return false. Doing so will also
allow you to simplify your while condition (do you see why?)
retval = 0;
counter++;

return retval;
You're missing brackets and/or using funky spacing so I can't quite tell
what you're trying to do here. Try taking my advice in the previous
paragraph and rewriting the rest of this with properly matched brackets.
}

return 0;
}

Im getting an ambigous call to overload on my square root function.
There are several different sqrt functions defined in cmath. Try
sqrt(static_cas t<double> (...)).

Also see:

http://www.dinkumware.com/manuals/re...math.html#sqrt

to see the various sqrt functions available.

Incidentally, rather than checking a <= sqrt(b) it's probably faster and
safer (by avoiding floating point inaccuracies) to check a*a <= b.
Other than that the program is just not working, can someone please
help me out here?


Give it another try and show us what you come up with.

Mark
Nov 9 '05 #2
br************@ gmail.com wrote:
Write a program that prompts the user to input a positive integer. It
should then output a message indicating whether the number is a prime
number. (Note: An even number is prime if it is 2. An odd integer is
prime if it is not divisible by an odd integer less than or equal to
the square root of the number.) I was given this assignment in my c++
class and I'm having trouble with it. I've looked at the professors lab
solutions but I just dont understand it. This is the code I have.

#include <iostream>
#include <cmath>

using namespace std;
int isprime(int);

int main()
{
int inputnumber;

cout << "Input a positive integer:";
cin >> inputnumber;

if (isprime(inputn umber))
cout << inputnumber << " is prime";
else
cout << inputnumber << " is not prime";
Missing }


int isprime(int inval);
Extra illegal ;


int retval = 1;
int counter = 2;
int inval;

while ((counter < sqrt(retval)) && retval != 0)
{
if (inval % counter == 0)
retval = 0;
counter++;

return retval;
}

return 0;
}

Im getting an ambigous call to overload on my square root function.
Other than that the program is just not working, can someone please
help me out here?


Well the loop is confused

1) It should be sqrt(inval) not sqrt(retval)

2) It should be counter <= sqrt(inval) not counter < sqrt(inval)

3) The ambiguous error message is probably because sqrt comes in two
version, one for float and one for double, and you provided neither.

4) Anyway you don't need sqrt

counter <= sqrt(inval)

is the same as

counter*counter <= inval

At least that's good enough for a newbie program.

5) You have put return retval in your loop for some reason best known to
yourself. If you look at the loop you *always* return retval from inside
the loop.

6) Anyway you don't need retval

while (counter*counte r <= inval)
{
if (inval % counter == 0)
return 1;
counter++;
}
return 0;

7) isprime is a boolean function so it should return a boolean not an
integer

bool isprime(int inval)
{
...
return true;
...
return false;
}

This should be a good lesson, in programming the details matter, its not
good enough to be 80% right, it has to be 100%.

john
Nov 9 '05 #3
Ok, I really appreciate your help on this guys. I changed a few things
and added in some comments. I'm still having a few problems compilling
this program though. It seems im having an error at my if statement...

if primenum(inputn umber)
cout << inputnumber << " is prime";
else
cout << inputnumber << " is not prime";
syntax error: identifier 'primenum'
illegal else without matching if

Nov 10 '05 #4
br************@ gmail.com wrote:
Ok, I really appreciate your help on this guys. I changed a few things
and added in some comments. I'm still having a few problems compilling
this program though. It seems im having an error at my if statement...

if primenum(inputn umber)
cout << inputnumber << " is prime";
else
cout << inputnumber << " is not prime";
syntax error: identifier 'primenum'
illegal else without matching if


In general it's always a good idea to post complete code because the
problem may not be what you think it is (or maybe there's more than one
problem). That said, your problem here is the "if" syntax which should be:

if (primenum(input number))
....

The condition needs to be enclosed in parentheses.
Nov 10 '05 #5
Mark, thank you so much for your quick reply. If you look up at the top
I had it correct, but I took your advice and re-wrote most of the
program and I didn't notice I had changed that. Thank you for the help.

Nov 10 '05 #6
I think you should break the entire problem up into easy to chew
chunks. Don't be afraid to write lots of functions. It makes writing
the program trivial. All of this retval, intval, counter stuff is
confusing, even for me. Here is how I would approach the problem:
Write a program that prompts the user to input a positive integer.
This tells me I need a function such as:

int PromptUser() {
cin >> n;
if (n <= 0) {
exit(1);
}
return n;
}
It should then output a message indicating whether the number is a prime number.

This indicates I need the following function:

void OutputMessage(b ool bIsPrime) {
if (bIsPrime) {
cout << "the number is prime" << endl;
}
else {
cout << "the number is not prime" << endl;
}
}
(Note: An even number is prime if it is 2.
bool IsNumberEven(in t n) {
return n % 2 == 0;
}

bool IsEvenNumberPri me(int n) {
assert(IsNumber Even(n)); // make sure it really is an even number
if (n == 2) {
return true;
}
else {
return false;
}
}
An odd integer is

prime if it is not divisible by an odd integer less than or equal to
the square root of the number.)

bool IsNumberOdd(int n) {
return !IsNumberEven(n );
}

bool IsDivisibleBy(i nt Dividend, int Divisor) {
return Dividend % Divisor == 0;
}

bool IsOddNumberPrim e(int n) {
assert(IsNumber Odd(n)); // make sure it really is an odd number
double dSquareRoot = sqrt(n);
// check divisibility against all odd numbers up to the square root.
for (int i=1; i <= dSquareRoot; ++i) {
if (IsNumberOdd(i) ) {
if (IsDivisibleBy( n, i)) {
return false;
}
}
}
return true;
}

I'll leave it to you to construct the rest of program.

I hope this helps.

Christopher Diggins
http://www.cdiggins.com
http://www.cpp-cookbook.com

Nov 10 '05 #7
br************@ gmail.com wrote:
Mark, thank you so much for your quick reply. If you look up at the top
I had it correct, but I took your advice and re-wrote most of the
program and I didn't notice I had changed that. Thank you for the help.


'I rewrote most of the program'

I'm impressed, you'll go far. Hanging around here I'm continually
frustrated by how many newbies are reluctant to do that. Of course
should you ever get a job programming your bosses will tell you not to
rewrite poor code but you'll do it anyway.

john
Nov 10 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3883
by: Roy J | last post by:
Hello everyone:) My name is Roy, I am new to Java and I have problem regarding to arrays. if you have time and like to help, please help. I am trying to make a program to deal with prime numbers, but I do not how to involve arrays with that. program generates prime numbers according to user input, and displays them in descending order. The user enters the number of prime numbers to be generated. The output is displayed 5 numbers per...
2
375
by: nicks | last post by:
Hi there ! i need a bit of help as i am a new c++ user to write a program. The program should ask the user n questions or until the user enters -1 to Exit (n should be a constant and it should be equal to the largest digit in your ID number; for example: if your id number is S0930350, n should be 9). The program should generate the following report. Total number of questions asked The number of questions correctly answered The number...
7
4897
by: newstips6706 | last post by:
1, 2, 3, 5, 7... PRIME Numbers ________________________________ Definitions What is a PRIME Number ?
3
1463
by: massdeletion101 | last post by:
I've made a program designed to find every prime number until it reaches the C++ maximum intager limit. I want it to be able to break the loop based on the press of a key. I need a funcion that tests the standard input stream for input before firing. I tried the cin.eof() function in the while loop, but that does not work right as it will merely just display none of the numbers and let me to press enter infinitely. Here is the program: ...
4
2315
by: cnixuser | last post by:
Hello, I am attempting to create a prime number detector that will identify all of the prime numbers within a specified range of numbers. The problem is, for some reason my program is not detecting any prime numbers and seems to be only to be printing one value of zero from the array that I am trying to store the prime numbers detected in. I believe the zero is coming from the value already stored in the array when I initialzed it, which means...
6
5291
by: UofFprogrammer | last post by:
For a fun challenge, I am trying to create a C++ program that will determine if a number is prime. I am getting to problems when I reach a large values (over 9 or so digits). How can I increase the number of digits i can use? For example, when i use the number 4362206209 (which I know for a fact is prime) it returns 2 as a factor, which it isn't. Eventually, I would like to get to long (50+ digit) numbers. I know this calculation would take...
1
2365
by: vekka | last post by:
Hi! Programming language: C I wondered if any of you are able to see what is wrong with my code. What I want to do is to find the union of a set of numbers. I use a singly linked list. and my union function is based on a simple merge algorithm. There are four different sets: even numbers, odd numbers, prime numbers and non prime numbers. When I run my program now, it prints out: Even or Odd numbers: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 .. 50 ...
4
2158
by: sigkill9 | last post by:
I'm trying to create a script that will accept a user entered integer and find only one set of prime numbers that add up to that integer but need some help. The script is supposed to only accept even numbers, and if it encounters an odd number it needs to exit with a "please enter only even numbers" message. I've made some progress on the script, but it still isnt quite rite. I already tried to code an error message for uneven input...
3
6292
by: sigkill9 | last post by:
I've been working on this script all weekend and am almost done with it accept for one last detail; implementing a "process another number?" prompt after a user input is processed. The script works like this: First, the user enters a number to test (to find the two prime numbers that make up that number). Next the program finds the numbers, outputs them, then quits. What I want to do is create a prompt after the number has been processed...
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8531
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8628
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.