Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Check prime numbers in C Programming

October 3, 2013 Posted by: GPA Views: 27620 0 comments

Problem

Write program to check that a numbers are prime or not from 2 to n where n is a user inputed number. 

Solution

A prime number is a number which is only evenly divisible by 1 and itself. In this example we will find all prime numbers from 2 to n. We'll prompt the user for number n. Using loop iteration, program'll check all numbers from 2 to n whether the number is prime. If it is prime, print out: " is prime".

Example:



#include <stdio.h>
#include <stdlib.h>
int Is_Prime(int checkNumber);
int main(int argc, char *argv[])
{
int n=0;
int i;

printf(
"Please, enter a number larger than two: ");//promt user to enter number
scanf("%d",&n);//read number from keyboard
for(i=2;i<=n;i++){
if (Is_Prime(i)==1){
printf("%d is prime\n",i);
}
}
system("PAUSE");//delay
return 0;
}
//function to check if number is prime
int Is_Prime(int checkNumber){
if ((checkNumber & 1) == 0) {
if (checkNumber == 2){
return 1;
}else{
return 0;
}
}
int i;
for (i = 3; (i * i) <= checkNumber; i += 2)
{
if ((checkNumber % i) == 0)
{
return 0;
}
}
return checkNumber !=1;
}

Output

prime numbers in C

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe