Question

EDIT: The question essentially asks to generate prime numbers up to a certain limit. The original question follows.

I want my if statement to become true if only these two conditions are met:

for i := 2; i <= 10; i++ {

    if i%i == 0 && i%1 == 0 {

    } else {

    }
}

In this case every possible number gets past these conditions, however I want only the numbers 2, 3, 5, 7, 11... basically numbers that are divisible only with themselves and by 1 to get past, with the exception being the very first '2'. How can I do this?

Thanks

Was it helpful?

Solution

It seems you are looking for prime numbers. However the conditions you described are not sufficient. In fact you have to use an algorithm to generate them (up to a certain limit most probably).

This is an implementation of the Sieve of Atkin which is an optimized variation of the ancient Sieve of Eratosthenes.

Demo: http://play.golang.org/p/XXiTIpRBAu

For the sake of completeness:

package main

import (
    "fmt"
    "math"
)

// Only primes less than or equal to N will be generated
const N = 100

func main() {
    var x, y, n int
    nsqrt := math.Sqrt(N)

    is_prime := [N]bool{}

    for x = 1; float64(x) <= nsqrt; x++ {
        for y = 1; float64(y) <= nsqrt; y++ {
            n = 4*(x*x) + y*y
            if n <= N && (n%12 == 1 || n%12 == 5) {
                is_prime[n] = !is_prime[n]
            }
            n = 3*(x*x) + y*y
            if n <= N && n%12 == 7 {
                is_prime[n] = !is_prime[n]
            }
            n = 3*(x*x) - y*y
            if x > y && n <= N && n%12 == 11 {
                is_prime[n] = !is_prime[n]
            }
        }
    }

    for n = 5; float64(n) <= nsqrt; n++ {
        if is_prime[n] {
            for y = n * n; y < N; y += n * n {
                is_prime[y] = false
            }
        }
    }

    is_prime[2] = true
    is_prime[3] = true

    primes := make([]int, 0, 1270606)
    for x = 0; x < len(is_prime)-1; x++ {
        if is_prime[x] {
            primes = append(primes, x)
        }
    }

    // primes is now a slice that contains all primes numbers up to N
    // so let's print them
    for _, x := range primes {
        fmt.Println(x)
    }
}

OTHER TIPS

Here's a golang sieve of Eratosthenes

package main
import "fmt"

// return list of primes less than N
func sieveOfEratosthenes(N int) (primes []int) {
    b := make([]bool, N)
    for i := 2; i < N; i++ {
        if b[i] == true { continue }
        primes = append(primes, i)
        for k := i * i; k < N; k += i {
            b[k] = true
        }
    }
    return
}

func main() {
    primes := sieveOfEratosthenes(100)
    for _, p := range primes {
        fmt.Println(p)
    }
}

The simplest method to get "numbers that are divisible only with themselves and by 1", which are also known as prime numbers is: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

It's not a "simple if statement".

If you don't mind a very small chance (9.1e-13 in this case) of them not being primes you can use ProbablyPrime from math/big like this (play)

import (
    "fmt"
    "math/big"
)

func main() {
    for i := 2; i < 1000; i++ {
        if big.NewInt(int64(i)).ProbablyPrime(20) {
            fmt.Printf("%d is probably prime\n", i)
        } else {
            fmt.Printf("%d is definitely not prime\n", i)
        }
    }
}

Just change the constant 20 to be as sure as you like that they are primes.

Simple way(fixed):

package main

import "math"

const n = 100

func main() {
    print(1, " ", 2)

L:  for i := 3; i <= n; i += 2 {
        m := int(math.Floor(math.Sqrt(float64(i))))
        for j := 2; j <= m; j++ {
            if i%j == 0 {
                continue L
            }
        }
        print(" ", i)
    }
}

just change the 100 in the outer for loop to the limit of the prime number you want to find. cheers!!

    for i:=2; i<=100; i++{


        isPrime:=true

        for j:=2; j<i; j++{

            if i % j == 0 {

                isPrime = false
            }
        }

        if isPrime == true {

            fmt.Println(i)
        } 
    }


}

Here try this by checking all corner cases and optimised way to find you numbers and run the logic when the function returns true.

package main

import (
    "math"
    "time"
    "fmt"
)

func prime(n int) bool {

    if n < 1 {
        return false
    }

    if n == 2 {
        return true
    }

    if n % 2 == 0 && n > 2 {
        return false
    }

    var maxDivisor = int(math.Floor(math.Sqrt(float64 (n))))

    //d := 3
    for d:=3 ;d <= 1 + maxDivisor; d += 2 {

        if n%d == 0 {
            return false
        }
    }
    return true
}
//======Test Function=====

func main() {
    // var t0 = time.Time{}
    var t0= time.Second
    for i := 1; i <= 1000; i++ {
        fmt.Println(prime(i))
    }
    var t1= time.Second
    println(t1 - t0)
}
package main

import (
    "fmt"
)

func main() {
    //runtime.GOMAXPROCS(4)

    ch := make(chan int)
    go generate(ch)
    for {
        prime := <-ch
        fmt.Println(prime)
        ch1 := make(chan int)
        go filter(ch, ch1, prime)
        ch = ch1
    }
}

func generate(ch chan int) {
    for i := 2; ; i++ {
        ch <- i
    }
}

func filter(in, out chan int, prime int) {
    for {
        i := <-in
        if i%prime != 0 {
            out <- i
        }
    }
}

A C like logic (old school),

package main
import "fmt"

func main() {
    var num = 1000
    for j := 2; j < num  ; j++ {
        var flag = 0
        for i := 2; i <= j/2  ; i++ {   
            if j % i == 0 {
                flag = 1
                break
            }
        }
        if flag == 0 {
            fmt.Println(j)
        }
    }

}

A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17. What is Prime Number? A Prime Number is a whole number that cannot be made by multiplying other whole numbers

A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. Go Language Program to Check Whether a Number is Prime or Not https://www.golanguagehub.com/2021/01/primenumber.html

Simple solution for generating prime numbers up to a certain limit:

func findNthPrime(number int) int {

    if number < 1{
        fmt.Println("Please provide positive number")
        return number
    }

    var primeCounter, nthPrimeNumber int

    for i:=2; primeCounter < number; i++{
        isPrime := true
        for j:=2; j <= int(math.Sqrt(float64(i))) && i != 2  ; j++{
            if i % j == 0{
                isPrime = false
            }
        }
        if isPrime{
            primeCounter++
            nthPrimeNumber = i
            fmt.Println(primeCounter, "th prime number is ", nthPrimeNumber)
        }
    }
    fmt.Println("Nth prime number is ", nthPrimeNumber)
    return nthPrimeNumber
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top