Prime Number

优质
小牛编辑
133浏览
2023-12-01

任何大于1且仅有两个因子1和数字本身的整数称为素数。 除了这两个数字,它没有正向除数。 例如 -

7 = 1 × 7

几个素数是 - 1,2,3,5,7,11等。

算法 (Algorithm)

这个程序的算法很简单 -

START
   Step 1 → Take integer variable A
   Step 2 → Divide the variable A with (A-1 to 2)
   Step 3 → If A is divisible by any value (A-1 to 2) it is not prime
   Step 4 → Else it is prime
STOP

伪代码 (Pseudocode)

我们可以按如下方式起草上述算法的伪代码 -

procedure prime_number : number
   FOR loop = 2 to number - 1
      check if number is divisible by loop
      IF divisible
         RETURN "NOT PRIME"
      END IF
   END FOR
   RETURN "PRIME"
end procedure

实现 (Implementation)

该算法的实现如下 -

#include <stdio.h>
int main() { 
   int loop, number;
   int prime = 1;
   number = 11;
   for(loop = 2; loop < number; loop++) {
      if((number % loop) == 0) {
         prime = 0;
      }
   }
   if (prime == 1)
      printf("%d is prime number.", number);
   else
      printf("%d is not a prime number.", number);
   return 0;
}

输出 (Output)

该方案的产出应该是 -

11 is prime number.