Prime Number program in C using sqrt (square root ) Function

Spread the love

In our previous blog post, we discussed What is prime number and C program to check given number is prime or not. but we used In-efficient way,  In this post I am going to write the same program in Efficient way. using square root function Instead of comparing all numbers from 2 to number/2.(we used this method in previous blog post).

Description :

This program accepts one positive number from the user. and try to check that number is a prime number or not. 

C Program to calculate prime number in efficient way using sqrt function:

  1. #include<stdio.h>
  2. #include<math.h>
  3. void main()
  4. {
  5.    int num,i;
  6.    int FLAG=1;
  7.    printf(“Enter any Positive Number : “);
  8.    scanf(“%d”,&num);
  9.    for(i=2;i<=sqrt(num);i++)
  10.    {
  11.       if(num%== 0)
  12.       {
  13.          FLAG = 0;
  14.          break;
  15.       }
  16.    }
  17.    if(FLAG == 1)
  18.    {
  19.       printf(“%d is Prime Number n,num);
  20.    }
  21.    else
  22.    {
  23.       printf(“%d is not a Prime Number n,num);
  24.    }
  25.    return;
  26. }

Output :

Prime Number program in C using sqrt function

Quick Notes:

  • Here i used sqrt() function. declaration of sqrt function found in math.h so don’t forget add that header file to our program. if you forget to add that header file you will get one warning message saying

 

warning: incompatible implicit declaration of built-in function ‘sqrt’ [enabled by default]  for(i=2;i<=sqrt(num);i++)

 

  • This program compilation is little different to other programs compilations because we need to pass library file name as compilation flag. you need to pass compilation flag -lm  to gcc while compiling this program otherwise you will get Linking Error. see below image for better understanding.
Possible Linking Errors and Warnings

Explanation :

look that the above picture I compiled program two times first time without using compilation flag (i.e lm) I got one warning and one linking error. 
i got warning because i removed math.h header file from the program.
Linking error is for we are using sqrt function, but that function is unknown to compiler (because we are not passing -lm here). where to look for that function if you pass lm to gcc it will look into math library and it contains sqrt definition. so we will not get that linking error.

The sqrt functions in math.h have implementations in libm.so (or .a for static linking), and libm is not linked in by default. So we need to pass compilation flag -lm to gcc to link those functions also.

Related Program on Prime Numbers:

More C programs:

Venkatesh Macha

Hi Guys, I am Venkatesh Macha. I am a programmer, Presently working as a Software Engineer. I love Linux and Open Source. Apart from that, I love to explore new technologies and things.

You may also like...

2 Responses

  1. harmanjot singh says:

    this program is wrong

Leave a Reply