Determining if a number is prime

后端 未结 20 1341
悲哀的现实
悲哀的现实 2020-11-30 03:05

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks w

20条回答
  •  死守一世寂寞
    2020-11-30 03:21

    Someone above had the following.

    bool check_prime(int num) {
    for (int i = num - 1; i > 1; i--) {
        if ((num % i) == 0)
            return false;
    }
    return true;
    }
    

    This mostly worked. I just tested it in Visual Studio 2017. It would say that anything less than 2 was also prime (so 1, 0, -1, etc.)

    Here is a slight modification to correct this.

    bool check_prime(int number)
    {
        if (number > 1)
        {
            for (int i = number - 1; i > 1; i--)
            {
                if ((number % i) == 0)
                    return false;
            }
            return true;
        }
        return false;
    }
    

提交回复
热议问题