Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C ตรวจสอบว่าตัวเลขเป็นผลรวมของจำนวนเฉพาะ 2 ตัวได้หรือไม่

ปัญหา: ตรวจสอบว่าจำนวนเต็มบวก N แสดงเป็นผลรวมของจำนวนเฉพาะ 2 ตัวได้หรือไม่

เช่น 20 = 3+17 = 13+7

อัลกอริทึม

  1. อ่าน num
  2. วน i = 2 ถึง num/2
  3. ถ้า i เป็นจำนวนเฉพาะ และ (num - i) เป็นจำนวนเฉพาะ → พิมพ์คู่ (i, num-i)
  4. ฟังก์ชัน sum(n) ตรวจสอบจำนวนเฉพาะ: วนหาร 2 ถึง n/2 ถ้าหารลงตัว → ไม่ใช่เฉพาะ

โค้ด 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("\nThe given %d can be expressed as the sum of %d and %d\n\n", num, i, num - i);
                flag = 1;
            }
        }
    }
    if (flag == 0)
        printf("The given %d cannot be expressed as the sum of two prime numbers\n", num);
    return 0;
}

int sum(int n) {
    int i, isPrime = 1;
    for (i = 2; i <= n / 2; ++i) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }
    return isPrime;
}

ตัวอย่าง Output

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