Petefic - 4 months ago 22

C Question

In my homework for my C class, we have to write a program that checks if an integer is prime. I am getting an error at the sqrt() function. My professor told me that num must be an integer and we must use the sqrt() function. I thought the problem was that the sqrt() function can't be used on an integer but my professor told me that it can, and that I was getting an error from something else. Do you guys see the problem?

`int primality(int num)`

{

int isprime;

/*check if num is prime*/

for (int i = 2; i <= sqrt(num); i++)

{

if (num % i == 0)

isprime = 0; /*is not prime*/

else

isprime = 1; /*is prime*/

}

if (isprime == 0)

return 0;

elseif (isprime == 1)

return 1;

}

EDIT:

Yes I am using math.h and compiling as C code.

The error msg is "Error: More than one instance of overloaded function "sqrt" matches the argument list.

Answer

The C language does not have "overloads". My bet is that you are compiling your code as C++, not C. If you're using GCC, compile with `gcc`

, not `g++`

. If you are using Visual Studio, there is an option in the properties of the project:

- right click on your project
- click properties
- click on C/C++
- click on advanced
- set the property "compile as" to C Code (/TC)

In either case, name your file with a `.c`

extension (*lowercase* 'c').

Indeed, in C there is only one `sqrt`

, defined as

```
double sqrt(double);
```

and integers convert to double.