Check Natural Number in JavaScript
What you’ll learn
- What natural numbers mean in beginner programming context.
- How to classify one integer using
n > 0. - How to list natural numbers in a simple range.
Overview
Under this tutorial rule, a natural number is any integer greater than zero.
Live preview
Algorithm
Goal: determine if num is natural using num > 0.
📜 Pseudocode
Pseudocode
function isNatural(num):
return num > 01
Check one integer
JavaScript
function isNatural(num) {
return num > 0;
}
const number = 42;
if (isNatural(number)) {
console.log(number + " is a natural number.");
} else {
console.log(number + " is not a natural number.");
}2
Print natural numbers from 1 to 10
JavaScript
function printNaturalsInRange(start, end) {
const parts = [];
for (let i = start; i <= end; i++) {
if (i > 0) {
parts.push(String(i));
}
}
console.log("Natural numbers in the range " + start + " to " + end + ":");
console.log(parts.join(" "));
}
printNaturalsInRange(1, 10);❓ FAQ
In this tutorial, a natural number means a positive integer: 1, 2, 3, and so on.
Some definitions include 0, some do not. This page uses n > 0, so 0 is not natural here.
No. Any value <= 0 is not natural under this rule.
No. Natural numbers are whole numbers only.
It keeps the condition in one place and makes calling code easier to read and test.
Single check is O(1). Printing a range is O(k) for k printed numbers.
Edge cases
Zero
n === 0
Not natural under this tutorial rule.
Non-integer
3.5
Not a natural number because it is not whole.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
| Single natural check | O(1) | O(1) |
| Print range | O(k) | O(k) for join buffer |
Summary
- Rule used: natural means
n > 0. - Patterns: single-value check and range listing.
Did you know?
In many school definitions, natural numbers start from 1. Some books include 0. This page uses n > 0 so code and wording stay consistent.
8 people found this page helpful
