C程序 通过创建一个函数来检查素数
在这里,我们将建立一个C程序,通过使用3种不同的方法创建一个函数来检查素数。
1.使用for循环进行素数计算
2.使用for循环进行非质数
3.使用while循环进行素数计算
输入:
n = 7
输出:
7 is a prime number
方法1:使用for循环
// C program to demonstrate whether
// a number is prime or not using
// for loop
#include <stdio.h>
// defining the function
int primenumber(int number)
{
int i;
// condition for checking the
// given number is prime or
// not
for (i = 2; i <= number / 2; i++) {
if (number % i != 0)
continue;
else
return 1;
}
return 0;
}
int main()
{
int num = 7, res = 0;
// calling the function
res = primenumber(num);
if (res == 0)
printf("%d is a prime number", num);
else
printf("%d is not a prime number", num);
}
输出
7 is a prime number
方法2:使用for循环处理非质数
// C program to demonstrate whether
// a number is prime or not using
// for loop
#include <stdio.h>
// defining the function
int primenumber(int number)
{
int i;
// condition for checking
// the given number is prime
// number or not
for (i = 2; i <= number - 1; i++) {
if (number % i == 0)
return 0;
}
return 1;
}
int main()
{
int num = 4, res;
// calling the function
res = primenumber(num);
if (res == 1)
printf("%d is a prime number", num);
else
printf("%d is not a prime number", num);
return 0;
}
输出
4 is not a prime number
方法3:使用while循环
// C program to demonstrate whether
// a number is prime or not using
// while loop
#include <stdio.h>
// defining the function
int primenumber(int number)
{
// condition for checking the
// given number is prime or
// not
int i = 2;
while (i <= number / 2) {
if (number % i == 0)
return 0;
else
i++;
}
return 1;
}
int main()
{
int num = 7, prime;
// calling the function
prime = primenumber(num);
// printing the result
if (prime == 1)
printf("%d is a prime number", num);
else
printf("%d is not a prime number", num);
return 0;
}
输出
7 is a prime number