แบบฝึกหัด Go
Prime Numbers in Go
Test whether a number is prime and list the primes up to 30.
สิ่งที่คุณจะได้เรียนรู้
- Trial division
- Stopping at the square root
- Building a slice
2 to 7
2prime
3prime
42 x 2
5prime
62 x 3
7prime
Only divisible by 1 and itself
A prime number is larger than 1 and can only be divided by 1 and itself. Write a function that tests one number, then use it in a loop.
It is enough to try divisors up to the square root of n, which is what divisor*divisor <= n checks. The loop in main appends every number for which isPrime returns true.
ประเด็นสำคัญ
- Numbers below 2 are not prime.
- Divisors up to the square root are enough.
- append collects the primes.
ตัวอย่าง Go ที่รันได้
main.go
package main
import "fmt"
func isPrime(n int) bool {
if n < 2 {
return false
}
for divisor := 2; divisor*divisor <= n; divisor++ {
if n%divisor == 0 {
return false
}
}
return true
}
func main() {
primes := []int{}
for n := 1; n <= 30; n++ {
if isPrime(n) {
primes = append(primes, n)
}
}
fmt.Println(primes)
fmt.Println("97 is prime:", isPrime(97))
}
[2 3 5 7 11 13 17 19 23 29]
97 is prime: trueฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- ตรวจสอบจำนวนเฉพาะ ตัดสินว่าตัวเลขเป็นจำนวนเฉพาะหรือไม่ ง่าย
- List Primes With a Sieve Find primes up to a limit by marking composite multiples. ปานกลาง