The need:
This program was asked me by a reader of this blog. This program takes 2 numbers from the user and prints all the prime numbers between them (inclusive both the numbers).
The code:
-------------------------------------------------------
-------------------------------------------------------
instead of only "cc file.c"
This program was asked me by a reader of this blog. This program takes 2 numbers from the user and prints all the prime numbers between them (inclusive both the numbers).
The code:
-------------------------------------------------------
#include<stdio.h> #include<math.h> int isPrime(int ); main() { int number1,i,number2; printf("enter a natural number.\n"); scanf("%d",&number1); printf("enter second natural number.\n"); scanf("%d",&number2); if(number1<1||number2<1) { printf("one of the numbers entered was not a natural number.\n"); exit(0); } printf("the prime numbers between %d and %d are =>\n\n",number1,number2); for(i=number1;i<=number2;i++) { if(isPrime(i)) { printf("%d\t",i); } } printf("\n\n"); } int isPrime(int x) //this function returns one if the { //input number x is prime else returns 0 int i,flag=1; if(x==1) //people say 1 is not a prime number return 0; else if(x==2) //people say 2 is a prime number return flag; else //just following the definition for the number greater than 2 for(i=2;i<=sqrt(x);i++) { if(x%i==0) { flag=0; break; } } return flag; }
-------------------------------------------------------
Remarks:
If you are using linux/unix to compile this program, add '-lm'(without quotes) after the compile command. Ex. : if the file name is file.c, give the command:
"cc file.c -lm"(without quotes) instead of only "cc file.c"
No comments:
Post a Comment
feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply