將一個數字表示為兩個素數之和的 C 程式。


問題

找出給定的數字是否可以表示為兩個素數之和。

給定一個正整數 N,我們需要檢查數字 N 是否可以表示為兩個素數之和。

解決方案

考慮以下示例:

20 可以表示為兩個素數 3 和 17 之和,13 和 7 之和。

20= 3+7

20= 13+7

演算法

參考以下演算法,將給定數字表示為兩個素數之和。

步驟 1 - 在執行時輸入要檢查的數字。

步驟 2 - 從 i = 2 重複到 (num/2)。

步驟 3 - 檢查 i 是否為素數。

步驟 4 - 如果 i 是素數,則檢查 (n - i) 是否為素數。

步驟 5 - 如果 (i) 和 (n - i) 都是素數,則給定數字可以表示為素數 i 和 (n - i) 的和。

示例

以下是將給定數字表示為兩個素數之和的 C 程式:

 線上演示

#include <stdio.h>
int Sum(int n);
int main(){
   int num, i;
   printf("Enter number: ");
   scanf("%d", &num);
   int flag = 0;
   for(i = 2; i <= num/2; ++i){
      if (sum(i) == 1){
         if (sum(num-i) == 1){
            printf("
The given %d can be expressed as the sum of %d and %d

", num, i, num - i);             flag = 1;          }       }    }    if (flag == 0)    printf("The given %d cannot be expressed as the sum of two prime numbers
", num);    return 0; } //check if a number is prime or not int sum(int n){    int i, isPrime = 1;    for(i = 2; i <= n/2; ++i){       if(n % i == 0){          isPrime = 0;          break;       }    }    return isPrime; }

輸出

執行上述程式時,會產生以下輸出:

Run 1:
Enter number: 34
The given 34 can be expressed as the sum of 3 and 31
The given 34 can be expressed as the sum of 5 and 29
The given 34 can be expressed as the sum of 11 and 23
The given 34 can be expressed as the sum of 17 and 17
Run 2:
Enter number: 11
The given 11 cannot be expressed as the sum of two prime numbers

更新於: 2021年3月26日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.