Number Programs
Number Programs — purpose and prerequisites
Number programs help practice integer checks, even/odd logic, divisibility, and bounds. JavaScript uses floating-point numbers for its number type; Number.isInteger is needed when the rule requires integers. Avoid depending on bitwise operations for large integers.
What you’ll learn
- Explain the purpose of number programs.
- Identify the typed contract, runtime responsibilities and common pitfalls.
- Run the example and extend its behavior with a practical exercise.
How the idea works
A prime has no integer divisor between 2 and its square root. The loop stops at divisor² > n, because any larger factor would have a smaller matching factor.
Do not classify 1 as prime, and do not assume all number values are safe integers.
Visualize the flow
Run the checked TypeScript example
This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.
TypeScript source
function isPrime(n: number): boolean {
if (!Number.isSafeInteger(n) || n < 2) return false;
for (let divisor = 2; divisor * divisor <= n; divisor++) {
if (n % divisor === 0) return false;
}
return true;
}
for (const n of [1, 2, 17, 21]) console.log(`${n}: ${isPrime(n)}`);Verified output
1: false
2: true
17: true
21: falseCompile: npx tsc --strict --target es2022 --module commonjs number-programs.ts; run: node number-programs.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.
Trace the execution
A prime has no integer divisor between 2 and its square root. The loop stops at divisor² > n, because any larger factor would have a smaller matching factor.
Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.
Common mistake and correction
Do not classify 1 as prime, and do not assume all number values are safe integers.
Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.
Your turn: extend the example
Write a function that returns every prime between 2 and 50 and checks the first and last values.
Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.
Check your understanding
Key idea to remember
A prime has no integer divisor between 2 and its square root. The loop stops at divisor² > n, because any larger factor would have a smaller matching factor.
Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.
Reaching the recap and completing the quizzes are separate milestones.