Are You A Prime Number

后端 未结 11 2185
甜味超标
甜味超标 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 08:03

    #include 
    #include 
    
    int IsPrime (int n) {
      int i, sqrtN;
      if (n < 2) { return 0; } /* 1, 0, and negatives are nonprime */
      if (n == 2) { return 2; }
      if ((n % 2) == 0) { return 0; } /* Check for even numbers */
      sqrtN = sqrt((double)n)+1; /* We don't need to search all the way up to n */
      for (i = 3; i < sqrtN; i += 2) {
        if (n % i == 0) { return 0; } /* Stop, because we found a factor! */
      }
      return n;
    }
    
    int main()
    {
      int n;
      printf("Enter a positive integer: ");
      scanf("%d",&n);
      if(IsPrime(n))
         printf("%d is a prime number.",n);
      else
         printf("%d is not a prime number.",n);
      return 0;
    }
    

提交回复
热议问题