Page 1 of 1

overloaded funtion with sqrt c++(helped)

Posted: Sun Mar 25, 2012 12:25 am
by vegiestirfrypizza
the error reads as "more than one instance of overloaded funtion sqrt in argument list" is there something wrong with #include <cmath>?

Code: Select all

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
cout<<"please enter a value to be evaluated as prime or not prime";
int x=0;
cin>>x;
int loop=2;
int prime=true;
while(loop == sqrt(x));<----this is the error.
{
if (x % loop==0)
	prime=false;
loop++;

}

if(prime)
	cout<<"number is prime";
else
	cout<<"number is not prime";



	system("PAUSE");
	return 0;
}

thank you for you're time.
error is in sqrt()

Re: overloaded funtion with sqrt c++

Posted: Sun Mar 25, 2012 12:43 am
by dandymcgee
First off the while([condition]) line should not end with a semi-colon. Second, sqrt() returns a double or a float depending on what type you pass as a parameter.

To get your code to compile you could simply cast the return value to an int and remove the semi-colon:

Code: Select all

while(loop == (int)sqrt(x))
Also, I'm not sure how you came up with this code but it's definitely not going to properly determine whether or not x is prime.

Here is an example prime test for your reference:

Code: Select all

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
	int num;
	cin >> num;
	
	if (num <=1)
		return false;
	else if (num == 2)		 
		return true;
	else if (num % 2 == 0)
		return false;
	else
	{
		bool prime = true;
		int divisor = 3;
		double num_d = static_cast<double>(num);
		int upperLimit = static_cast<int>(sqrt(num_d) +1);
		
		while (divisor <= upperLimit)
		{
			if (num % divisor == 0)
				prime = false;
			divisor +=2;
		}
		cout << num << (prime) ? " is prime." : " is not prime.";
	}
	
	cin.get();
}

Re: overloaded funtion with sqrt c++

Posted: Sun Mar 25, 2012 1:18 am
by vegiestirfrypizza
thanks, i actually got it from a c++ book, maybe its not the best resource...not the assignment every line of code you see is in fact, not actually mine although it would be just as bad. but yeah, thank you for a better prime number code, and thanks again. :worship: