Print Numbers from 1 to n

easy Programming Basics

Problem

Read n. Print the numbers 1, 2, ..., n separated by a space on one line.

Constraints

  • 1 <= n <= 10^5

Examples

Input

5

Output

1 2 3 4 5

Solutions

Best approachTime O(n)Space O(n)

A for loop has three parts: the start (1), the end condition (<= n) and the step (+1). Many beginners stop at n - 1 because they forget that range in Python excludes the end value.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process a number.
 * Input   : One integer n.
 * Output  : The numbers from 1 to n.
 * Approach: A counting loop.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(long n) {
        // Step 1: The result array has n places. We fill place i with the number i + 1.
        int[] result = new int[(int) n];
        for (int i = 0; i < result.length; i++) {
            result[i] = i + 1;
        }
        return result;
    }

    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        System.out.println(Arrays.stream(solve(n)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. Is the end value included in range()?