Instead of trying to get a performance increase with a faster solution let's writereview your program and try to make it a solid one.
Check this outexample:
var a int = 0 // 0
var b int // default int value is 0, simularsimilar to above
var c = 0 // type is int, simularsimilar to above
d := 0 // same
The latter is short and nice, I suggest you to stick to it. var
notation is required in package block (globals), when explicit type is needed and to overcome variable shading.
When overflow accuresoccurs the loop condition will be falsy and the loop will terminate.
To take it futherfurther it is better not to expect intint
overflow and use MaxInt* constants from math package. Apart from guaranteed proper uintuint
overflow there is nothing solid about intint
, so it is better not to abuse itits behavior.
Let's take it futherfurther. After the inner loop you test the prime variable and print the current_prime number. So when you get current_prime % i == 0
as true you already know current_prime is not a prime number and you need to continue the outer loop. For such purpose Golang has labels that perfectly solve the task:
Finally lets choose the appropriate types for our task. Since we don't need the signed numbers we can use uint
instead of int
. AlsoBetter, lets use uint64
directly to guaranty the maximum availiableavailable type. The nice thing about unsigned numbers is that Golang guarantees that they will properly overflow properly so we can check for zero value to terminate the loop.
Example rewrite
Here follows a possible rewrite of your original program:
Nice things about the rewriteThings accomplished:
- only two variables
- proper type istypes are used
- overflow is handled
- no hacks