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条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?