ProgramGuru

Number Programs

Start with Number Programs

Learn number programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of number programs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Number exercises strengthen comparisons, remainder, loops and edge-case handling. Start with even/odd checks and move toward digit counting and simple divisor tests.

The example checks primality without relying on a math-library square root. Values below two are not prime.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for example numbersOnly possible divisors up to the square root need testing.Read numberStep 1Reject n < 2Step 2Check divisorsStep 3Classify primeStep 4Only possible divisors up to the square root need testing.
Only possible divisors up to the square root need testing.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func isPrime(n int) bool {
	if n < 2 {
		return false
	}
	for d := 2; d <= n/d; d++ {
		if n%d == 0 {
			return false
		}
	}
	return true
}
func main() {
	for _, n := range []int{1, 2, 9, 17} {
		fmt.Printf("%d prime: %t\n", n, isPrime(n))
	}
}

Output

1 prime: false
2 prime: true
9 prime: false
17 prime: true

Trace what the program does

1 is rejected by the n < 2 rule; 2 has no possible divisors to test; 9 is divisible by 3; 17 passes each tested divisor.

Avoid common mistakes

  • Always handle zero, one and negative inputs in prime checks.
  • Testing all divisors through n is correct but does unnecessary work.

Try it yourself

Print all prime numbers from 1 to 30 using isPrime.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which number is not prime?
Choose one answer. You can try again.

Answer and explanation

1

Correct. 1 is rejected by the n < 2 rule; 2 has no possible divisors to test; 9 is divisible by 3; 17 passes each tested divisor.

What you should remember

You have practiced Number Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Mathematical Programs →