Prime numbers. Go newbie

Doing a great Go class at Udemy and to practice im trying to migrate some Python scripts to Go. There is a very simple script im trying to make, that basically find the prime / non-prime numbers on a range.

Appreciate if someone could point out what im doing wrong…

Im able to detect the non-primes fine (code below):

package main

import "fmt"

func main() {
	var numbers int
	fmt.Print("please enter the number you want analyzed? ")
	fmt.Scan(&numbers)
	for i := 1; i < numbers; i++ {
		check(i)
	}
}

func check(numbers int) {
	if numbers > 1 {
		for i := 2; i < numbers; i++ {
			if numbers%i == 0 {
				fmt.Println(numbers, "isnt a prime number //", i, "times", numbers/i, "is", numbers)
				break
			}
		}
	} else {
		fmt.Println(numbers, "isnt a prime number")
	}
}

Once I put an else statement to show the prime numbers, the program blows up. (below).

func check(numbers int) {
	if numbers > 1 {
		for i := 2; i < numbers; i++ {
			if numbers%i == 0 {
				fmt.Println(numbers, "isnt a prime number //", i, "times", numbers/i, "is", numbers)
				break
			} else {
				fmt.Println(numbers, "its prime!") // ADDED THIS!
			}
		}
	} else {
		fmt.Println(numbers, "isnt a prime number")
	}
}

Your logic is off a bit. Think about the if statement you added - tey walking through it in your head or on paper if numbers is 7. That else statement will execute like 6 times.

If you want more info on how to fix it I can help but given that you are doing this to practice I won’t post anymore unless asked. I want you to have a chance to debug :slight_smile:

1 Like

Hi @joncalhoun
I already cracked my head on this. Not having the “while” loop is freezing my brain. Can you please tell me how an experienced Go programmer would do it?
Thx

There is a while in go, just that it is written out for.

for i <= 10 {
  i++
}

Try running this: https://play.golang.org/p/sugffCQzHH

See how the print statement prints out 5 different times? That is because a number is NOT prime if it is divisible by any number other than 1 and itself, but you have to check ALL numbers from 2 to sqrt(number) to see if a number is prime (technically you don’t need to check that many numbers but that is a minor detail here). Your code goes from 2 to numbers - 1 which is fine, just slightly slower. Your real issue stems from the fact that you are declaring a number as prime before that ever happens.

How can you change your code so that it only prints “this is a prime” if all numbers from 2 to sqrt(numbers) are checked?

PS - It honestly looks like your problem isn’t with Go, but is with your logic being used. I’m unclear how a while loop would change this.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.