duanmeng1858 2016-10-10 02:46
浏览 10
已采纳

素数程序给出错误答案

I recently created a program which will tell you if a number is prime or not. It gets all answers right but the prime number of 9.

package main

import "fmt"

func isPrime(num int) bool {
    for x := 2; x > 1; x++ {
        if num%2 == 0 {
            return false
        } else {
            return true
        }
    }
    return true
}

func main() {
    fmt.Printf("is it a prime number: %v 
", isPrime(9))
}

What is the problem?
Thanks in advance!

  • 写回答

3条回答 默认 最新

  • dongyan4424 2016-10-10 05:42
    关注

    1- Here is the working version of your code: try it on The Go Playground.

    package main
    
    import "fmt"
    
    func isPrime(num int) bool {
        if num < 2 {
            return false
        }
        for x := 2; x < num; x++ {
            if num%x == 0 {
                return false
            }
        }
        return true
    }
    
    func main() {
        fmt.Printf("is it a prime number: %v 
    ", isPrime(9))
    }
    

    2- The only even prime is 2, so it is better to check it first:

    if n == 2 {
        return true
    }
    

    Then there is no other even prime number: remove them all, and there is no prime number less than 2:

    if n < 2 || n&1 == 0 {
        return false
    }
    

    and you don't need to check more than square root of n:

    sqrt := int(math.Sqrt(float64(n)))
    

    And now you may start from 3, with just odd numbers (i += 2):

    for i := 3; i <= sqrt; i += 2 {
        if n%i == 0 {
            return false
        }
    }
    

    Try it on The Go Playground:

    package main
    
    import (
        "fmt"
        "math"
    )
    
    func isPrime(n int) bool {
        if n == 2 {
            return true
        }
        if n < 2 || n&1 == 0 {
            return false
        }
        sqrt := int(math.Sqrt(float64(n)))
        for i := 3; i <= sqrt; i += 2 {
            if n%i == 0 {
                return false
            }
        }
        return true
    }
    
    func main() {
        fmt.Printf("is it a prime number: %v 
    ", isPrime(9))
        for i := 0; i < 120; i++ {
            if isPrime(i) {
                fmt.Print(i, " ")
            }
        }
        fmt.Println()
    }
    

    output:

    is it a prime number: false 
    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
    

    See:
    Prime number
    Generating primes

    enter image description here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题