2016-08-14 3 views
-6
#include <stdio.h> 
#include <conio.h> 

void main() { 
    int a, n, x; 
    clrscr(); 
    printf("enter a number"); 
    scanf("%d", &a); 
    n > 1; 
    a != n && n < a; 
    if (a/n == x) 
     printf("a is not a prime no"); 
    else 
     printf("a is a prime no"); 
} 

これを実行して合成番号をつけても、素数として表示されます。このコードで何が問題になっていますか? (与えられた数字が素数であるかどうかをチェックする)

+3

用についてa linkです。 – SurvivalMachine

+1

そこにループを記述することを忘れていませんか? 'n'と' x'も初期化されません。 'for 'ループと、一般的な基本Cについて読むことができます。あなたのコードは意味がありませんが、何らかのループが欲しいと思いますが、どうやって何がわからないのでしょうか。言い換えれば、**いくつかの基本的なCを最初に学ぶ**。 –

答えて

1

ifステートメントは決してtrueではないnxへのデュオは初期化されません。したがって、あなたは他人を帰ってくるだけです。さらに、式n>1;a != n && n < a;は、何もコンパイルされていないブールを返します。その場合は、forループを使用する必要があります。 !; `と` = N &&n は1:ここでは

は、これらの行には何もしないループ

int main() 
{ 
    int a,n,x = 0; 

    printf("enter a number: "); 
    scanf("%d",&a); 
    for(n=2; n<=a/2; ++n) 
    { 
     if(a%n==0) 
     { 
      x=1; 
      break; 
     } 
    } 
    if (x==0) 
     printf("",n); 
    else 
     printf("a is not a prime no");  
    return 0; 
} 
+0

私がiを宣言したとしても、出力(何も入力していないとき)は来ません。 – ash22

-1
#include<stdio.h> 
#include<conio.h> 
int main() 
{ 
    clrscr();//clearing the screen 
    int n,x=2,count=0;//Here count is initialised to 0,if it is not prime it remains the same,else it will be equal to 1.You will understand this as you go down 
    //A number is a prime number if it is not divisible by any other number from 2 and the number before it. 
    printf("Enter a number : "); 
    scanf("%d",&n); 
    while(x<n)//As this checking process should continue till the number just preceding it 
    { 
     if(n%x==0)//checking if the number n is divisible by x or not 
     { 
      count++;//IF divisible,there is no meaning in continuing,So we are coming out of the loop by incrementing the variable "count" 
      break; 
     } 
     else 
     x++; 
    } 
    if(count==0) 
    { 
     printf("%d is a prime number",n); 
     return 0;//Here if number is prime,There is no need to go further and execute till end,To reduce time complexity ,We will write a return statement to stop executing the code. 
    } 
    printf("%d is not a prime number",n); 
    return 0; 

} 
関連する問題