The c language calculates all primes in a given range
- 2020-05-17 06:07:07
- OfStack
Program functions:
Enter an integer and print out all primes within that integer.
Example program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
bool IsPrime(int x)
{
bool bResult = false;
int i, k;
k = (int)sqrt(x);
for (i = 2; i <= k; i++)
{
if (x % i == 0)
{
break;
}
}
if (i > k)
{
bResult = true;
}
else
{
bResult = false;
}
return bResult;
}
int main()
{
int a = 0;
int b = 0;
int i = 0;
printf(" Please enter the 1 Integers: ");
scanf("%d",&a);
for (i = 3; i <= a; i++)
{
if (IsPrime(i))
{
printf("%d\n",i);
}
}
system("pause");
return 0;
}
Program analysis:
1, IsPrime () function is used to determine whether an integer is prime. If it is, true is returned; otherwise, false is returned. In this function, because the C library function sqrt () is called, #include is included in the header file.
2, the scanf_s () function is used to get the data entered by the user and save this data into a local variable.
Summary:
1, math. h header file declares some common mathematical operations, such as power, square root, etc. If you want to use the C standard library of functions, you need to include the header file for the function.
2. We can use the scanf() function to get data from the terminal.