C language to determine whether a number is prime __c language

Source: Internet
Author: User

The so-called prime is the number of numbers that cannot be divisible by any other integer except 1 and itself.

To judge a number n (n>=3) method: N as dividend, will be 2 to (n-1) each integer divisor, if all can not be divisible, then n is prime.

Algorithm Analysis:

S1: Enter value for n

s2:i=2 (i as divisor)

S3:n by I, the remainder r,r=0, which means that n can be divisible by I, then N is not prime, the algorithm ends.

s4:i=i+1 if i<=n-1, returns S3, otherwise n is prime.

Code:

#include <stdio.h>


int main (void)
{
int i,j;
int temp;
scanf ("%d", &i);
for (j=2;j<=i-1;j++)
{
if (i%j==0)
{
printf ("not prime. \ n");
return 0;
}


}
printf ("is prime. \ n");
return 0;
}

Improvement: In fact, N does not need to be divided by 2 to (n-1) integers, only divisible by 2 to N/2, or even divisible by 2 to (n^ (1/2)). If I<=SQRT (n), returns S3, otherwise the algorithm ends.

Code

#include <stdio.h>


int main (void)
{
int i,j;
int temp;
scanf ("%d", &i);
for (j=2;j<=i-1;j++)
{
if (i%j==0)
{
printf ("not prime. \ n");
return 0;
}


}
printf ("is prime. \ n");
return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.