Determining if a number is prime

后端 未结 20 1361
悲哀的现实
悲哀的现实 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:17

    I came up with this:

    int counter = 0;
    
    bool checkPrime(int x) {
       for (int y = x; y > 0; y--){
          if (x%y == 0) {
             counter++;
          }
       }
       if (counter == 2) {
          counter = 0; //resets counter for next input
          return true; //if its only divisible by two numbers (itself and one) its a prime
       }
       else counter = 0;
            return false;
    }
    

提交回复
热议问题