这段代码有什么问题? (检查给定数字是否为素数)

时间:2016-08-14 09:55:41

标签: c

#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");
}

如果我运行它并输入一个复合数字,它仍会显示为素数。

2 个答案:

答案 0 :(得分:1)

您的if语句永远不会真实地n并且x未初始化。因此,您只能将其他人作为回报。此外,你的表达式n>1;a != n && n < a;会返回一个没有任何东西的bool。在这种情况下,您需要使用for循环。

以下是a link关于for循环

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;
}

答案 1 :(得分:-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;

}