Is there a simple algorithm that can determine if X is prime?

后端 未结 16 1521
离开以前
离开以前 2020-12-01 00:32

I have been trying to work my way through Project Euler, and have noticed a handful of problems ask for you to determine a prime number as part of it.

  1. I kno

16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 00:43

    Here is a simple primality test in D (Digital Mars):

    /** 
     * to compile:
     * $ dmd -run prime_trial.d
     * to optimize:
     * $ dmd -O -inline -release prime_trial.d 
     */
    module prime_trial;
    
    import std.conv : to;  
    import std.stdio : w = writeln;
    
    /// Adapted from: http://www.devx.com/vb2themax/Tip/19051 
    bool 
    isprime(Integer)(in Integer number) 
    {
      /* manually test 1, 2, 3 and multiples of 2 and 3 */
      if (number == 2 || number == 3)
        return true;
      else if (number < 2 || number % 2 == 0 || number % 3 == 0)
        return false;
    
      /* we can now avoid to consider multiples 
       * of 2 and 3. This can be done really simply 
       * by starting at 5 and incrementing by 2 and 4 
       * alternatively, that is: 
       *    5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, ...    
       * we don't need to go higher than the square root of the number */
      for (Integer divisor = 5, increment = 2; divisor*divisor <= number; 
           divisor += increment, increment = 6 - increment) 
        if (number % divisor == 0)
          return false;
    
      return true;  // if we get here, the number is prime
    }
    
    /// print all prime numbers less then a given limit
    void main(char[][] args) 
    {
      const limit = (args.length == 2) ? to!(uint)(args[1]) : 100;
      for (uint i = 0; i < limit; ++i) 
        if (isprime(i))
          w(i);
    }
    

提交回复
热议问题