#!/usr/bin/env bash

if [ $# -ne 1 ]; then
    echo "Usage: $0 <upper_limit>"
    exit 1
fi

upper_limit=$1

# Create an array to store whether each number is prime or not
declare -a is_prime

# Initialize the array to assume all numbers are prime initially
for ((i = 2; i <= upper_limit; i++)); do
    is_prime[$i]=true
done

# Apply the Sieve of Eratosthenes algorithm
for ((i = 2; i * i <= upper_limit; i++)); do
    if [ "${is_prime[$i]}" = true ]; then
        for ((j = i * i; j <= upper_limit; j += i)); do
            is_prime[$j]=false
        done
    fi
done

# Print the prime numbers in a single line with space separation
for ((i = 2; i <= upper_limit; i++)); do
    if [ "${is_prime[$i]}" = true ]; then
        # if number is 2, print it without space before
        if [ $i -eq 2 ]; then
            echo -n "$i"
        # print number after a space
        else
            echo -n " $i"
        fi
    fi
done
