ปัญหา
หาคำตอบว่าจำนวนที่กำหนดสามารถแสดงผลเป็นผลรวมของจำนวนเฉพาะสองตัวได้หรือไม่
จากจำนวนเต็มบวก 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("\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;
}
//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