Go अभ्यास

Prime Numbers in Go

Test whether a number is prime and list the primes up to 30.

  • शुरुआती
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • 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.

मुख्य बातें

  1. Numbers below 2 are not prime.
  2. Divisors up to the square root are enough.
  3. append collects the primes.

चलने योग्य Go उदाहरण

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))
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
[2 3 5 7 11 13 17 19 23 29]
97 is prime: true

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Strings →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज