Results 1 to 2 of 2

Thread: basic C question (kdevelop)

  1. #1
    deguss_h NNTP User

    Default 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.
    Code:
    double n = sqrt(64);
    If the function sqrt() is used in the form as follows and it doesn't work.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    long is_prime(long n);
    
    int main(int argc, char *argv[]){
    	
    	long n;
    			
    	do {
    	printf("\n\n\n\b");
    	printf(	"Welcome to the is_prime? program!\n\n"
    		"Enter you number which should be checked:\n"
    		"\tn = ");
    	scanf("%ld",&n);
    	getchar();
    	
    	if (n>0){
    		if (is_prime(n))
    			printf("\n\n\t%ld is a valid prime!\n\n",n);
    		else 
    			printf("\n\n%ld is NOT a prime.\n\n",n);
    	}
    	else printf("\n\nInvalid input!\n\n");
    	} 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.
    Last edited by deguss_h; 19-Oct-2008 at 13:45. Reason: typing error

  2. #2
    Join Date
    Mar 2008
    Location
    San Diego (California)
    Posts
    475

    Default Re: basic C question (kdevelop)

    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
    ~ There are 10 types of people. Those who understand binary, and those who don't. ~

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •