문제
주어진 숫자를 두 소수의 합으로 표현할 수 있는지 알아보세요.
양의 정수 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