Are You A Prime Number

后端 未结 11 2207
甜味超标
甜味超标 2021-02-10 07:39

I\'ve been interested in the problem of finding a better prime number recognizer for years. I realize this is a huge area of academic research and study - my interest in this i

11条回答
  •  我寻月下人不归
    2021-02-10 07:54

    You can make small cuts to your algorithm without adding too much code complexity. For example, you can skip the even numbers on your verification, and stop the search as soon as you find a factor.

    if (input < 2 || (input != 2 && input % 2 == 0))
      factorFound = 1;
    
    if (input > 3)
      for (i = 3; i <= ceiling && !factorFound; i += 2)
        if (input % i == 0)
          factorFound = 1;
    

    Regarding the complexity, if n is your input number, wouldn't the complexity be O(sqrt(n)), as you are doing roughly at most sqrt(n) divisions and comparisons?

提交回复
热议问题