Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,974 questions

51,918 answers

573 users

How to check if a number is prime in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"math"
	"math/rand"
	"time"
)

func isPrime(num int) bool {
	if num == 0 || num == 1 {
		return false
	}

	for p := 2; p <= int(math.Round(math.Sqrt(float64(num)))); p++ {
		if num % p == 0 {
			return false
		}
	}

	return true
}

func main() {
	rand.Seed(time.Now().UnixNano())

	for i := 1; i <= 20; i++ {
		n := rand.Intn(100) + 1
		if isPrime(n) {
			fmt.Printf("%d - Prime\n", n)
		} else {
			fmt.Printf("%d - NOT Prime\n", n)
		}
	}
}


/*
run:

86 - NOT Prime
96 - NOT Prime
64 - NOT Prime
79 - Prime
40 - NOT Prime
58 - NOT Prime
58 - NOT Prime
61 - Prime
81 - NOT Prime
100 - NOT Prime
13 - Prime
69 - NOT Prime
35 - NOT Prime
24 - NOT Prime
52 - NOT Prime
88 - NOT Prime
71 - Prime
72 - NOT Prime
62 - NOT Prime
46 - NOT Prime

*/

 



answered Oct 28, 2024 by avibootz
...