473,394 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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(inputnumber))
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 7351
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(inputnumber))
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_cast<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(inputnumber))
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*counter <= 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(inputnumber)
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(inputnumber)
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(inputnumber))
....

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(bool 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(int n) {
return n % 2 == 0;
}

bool IsEvenNumberPrime(int n) {
assert(IsNumberEven(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(int Dividend, int Divisor) {
return Dividend % Divisor == 0;
}

bool IsOddNumberPrime(int n) {
assert(IsNumberOdd(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
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...
2
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...
7
by: newstips6706 | last post by:
1, 2, 3, 5, 7... PRIME Numbers ________________________________ Definitions What is a PRIME Number ?
3
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...
4
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...
6
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...
1
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...
4
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...
3
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...

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.