basic C question (kdevelop)

Hi everybody!

I’m new here, and need a bit of help to solve a simple problem. I wrote a program to check if a number you entered is a prime or not.
To be efficient you need only to check from 3 to the divisors n=sqrt(m), where m is the number you entered.
If I use sqrt() in the form follows, it normally works.

double n = sqrt(64);

If the function sqrt() is used in the form as follows and it doesn’t work.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

long is_prime(long n);

int main(int argc, char *argv]){
	long n;
	do {

	printf(	"Welcome to the is_prime? program!

		"Enter you number which should be checked:
		"	n = ");
	if (n>0){
		if (is_prime(n))

	%ld is a valid prime!


%ld is NOT a prime.

	else printf("

Invalid input!

	} while (n!=0);

  return EXIT_SUCCESS;

long is_prime(long n){
	long i;
	if (n==4) 
		return 0;
	//for (i=3; i<n; i+=2){
	for (i=3; i<sqrt((double)(n)); i+=2){
		if (!(n%i))
			return 0;	//no prime
	return 1;	// prime	

Error msg: ue1_test.o: In function is_prime': /home/deguss/TUW/prog1/ue1_test/ue1_test/src/ue1_test.c:62: undefined reference to sqrt’

Thank you for any help.

you need to link with -lm
for instance

  • cc mathprog.c -o mathprog -lm*

in that way it will work (i tested myself)
You can also see
man sqrt
and it will tell you “link with -lm”
Good luck with your program :slight_smile: