Show all primes in go I'm trying to go through Adrian simple programming tasks; Elementary task 8     It's basically asking for an infinite loop to print every prime number as it finds it. 

Are there too many if statements? Call it intuitive knowledge, but something is just bugging me, like I'm missing something. Like, I can remove one of the if statements. So I'm wondering what you guys will find.

package main

import "fmt"

func main() {
    var current_prime int
    var prime bool
    current_prime = 0

    for {
        prime = true
        current_prime++

        for i := 2; i &lt; current_prime; i++ {
            if current_prime % i == 0 {
                prime = false
                i = current_prime
            }
        }

        if prime {
            fmt.Println("found prime:", current_prime);
        }
    }
}
Simple Programming Problems
  
  Write a program that prints all prime numbers. (Note: if your
  programming language does not support arbitrary size numbers, printing
  all primes up to the largest number you can easily represent is fine
  too.)




Your program says one is prime. That is not correct.

The only even prime number is two. You don't appear take advantage of that. That is inefficient.

A number can only be divisible by a number less than or equal to its square root. You don't appear take advantage of that. That is inefficient.

You are asked to "[print] all primes up to the largest number you can easily represent." In Go, type int is either 32 or 64 bits. You don't guarantee the largest number by using type int64. Your program is not correct.

You have no program termination condition. Your program is not correct.

And so on.



For example, fixing your code,

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println("prime numbers:")
    fmt.Println(2)

    for n := int64(3); n &gt; 0; n += 2 {
        prime := true

        r := int64(math.Sqrt(float64(n))) + 1
        for i := int64(3); i &lt; r; i += 2 {
            if n%i == 0 {
                prime = false
                break
            }
        }

        if prime {
            fmt.Println(n)
        }
    }
}




To provide a measure of performance, the results from a Go benchmark for all prime numbers up to 32,771:

BenchmarkPeterSO-4           500       2661556 ns/op
BenchmarkIbnRushd-4            3     492864429 ns/op