我编写了一个程序来查找所有小于用户输入整数的质数。但是,它只是挂起。我假设使用所有这些继续,那不是一团糟,我已经制作了意大利面条代码...有人可以帮助我吗?

 /*takes integer input, displays all primes less than that integer*/
#include <stdio.h>

int main(void) {
    unsigned int num_in, test_num = 0, divisor = 0;
    _Bool primestate = 0;
    printf("Please enter an integer.\n");
    scanf("%d", &num_in);

    while(test_num < num_in) {
        while(divisor < test_num) {
            if(test_num % divisor == 0) {
                primestate = 1;
            }

            test_num++;
        }
        if(primestate == 1) {
            printf("%d is prime and less than %d.\n", test_num, num_in);
        } else {
            continue;
        }
    }

    return 0;
}

最佳答案

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    unsigned int num_in, test_num, divisor;
    bool primestate;
    printf("Please enter an integer.\n");
    scanf("%u", &num_in);

    if(2 < num_in)
        printf("\n%u\n", 2);
    for(test_num = 3; test_num < num_in; test_num += 2){
        primestate = true;
        for(divisor=3; divisor * divisor <= test_num ; divisor += 2) {
            if(test_num % divisor == 0) {
                primestate = false;
                break;
            }
        }
        if(primestate) {
            printf("%u\n", test_num);
        }
    }

    return 0;
}

关于c - 素数小于整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24640580/

10-13 07:15