[英]The full output is not being printed
我沒有得到這個程序的 output,請幫助問題:雙素數是連續的奇數,它們都是素數。 編寫一個程序,輸入兩個正整數 A 和 B,並輸出 A 到 B 范圍內的所有孿生素數。
代碼是:
#include <stdio.h>
int main(){
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if(num1>num2){
temp=num1;
for(i=num2;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j!=0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k!=0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num2){
printf("\n%d and %d",i,i+2);
}
}
}
else{
temp=num2;
for(i=num1;i<temp;i=i+1){
int j;
for(j=2;j<i;j=j+1){
if(i%j==0){
p1=1;
}
}
int k;
for(k=2;k<(i+2);k=k+1){
if((i+2)%k==0){
p2=1;
}
}
if(p1==1 && p2==1 && (i+2)<=num1){
printf("\n%d and %d",i,i+2);
}
}
}
return 0;
}
OUTPUT:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\shaun\OneDrive\Desktop> cd "c:\Users\shaun\OneDrive\Desktop\c programming\programs\" ; if ($?) { gcc twin_primes.c -o twin_primes } ; if ($?) { .\twin_primes }
Enter 2 numbers: 8 19
Twin prime numbers are:
PS C:\Users\shaun\OneDrive\Desktop\c programming\programs>
if(p1==1 && p2==1 && (i+2)<=num2)
if(p1==1 && p2==1 && (i+2)<=num1)
您在上述 2 個條件下混淆了 num2 和 num1 。
如果您使用num1
而不是num2
和num2
而不是num1
,您將獲得 output。
除此之外,代碼中還有幾個邏輯錯誤。
p1
和p2
要解決上述 2 個問題,我建議您了解有關查找素數的更多信息。 我將在下面添加一些資源,請檢查。
另一件事,你基本上寫了兩次相同的代碼。 您可以通過在第一個大於第二個時交換 2 個給定值來使其更簡單。
最后,我在這里給出一個示例代碼。 這是為您的問題編寫簡單但易於理解的解決方案的方法之一。
示例代碼:
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num)
{
for(int i = 2; i * i <= num; i++)
{
if (num % i == 0) return false;
}
return true;
}
int main()
{
int num1,num2,temp,i,p1,p2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
p1=0;
p2=0;
printf("Twin prime numbers are:");
if (num1 > num2)
{
// swap the numbers. always keeping the first as the smaller one
int temp = num1;
num1 = num2;
num2 = temp;
}
if (num1 == 1) num1++; // ignoring 1
for(int i = num1; i <= num2 - 2; i++) // running the loop till num2 - 2, so we won't have to check whether i + 2 <= num2
{
if (isPrime(i) && isPrime(i+2))
{
printf("\n%d and %d",i,i+2);
}
}
return 0;
}
請查看以下 URL 以了解有關質數和交換值的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.