easyBasic Math Concepts

Print all Divisors

List all positive integers that divide n without a remainder.

Work through the cases

3 examples

Input notation

An integer n, where 1 <= n <= 1000000.

Expected result

Divisors in increasing order, separated by spaces.
Case 1

Input

12

Expected output

1 2 3 4 6 12
Case 2

Input

7

Expected output

1 7
Case 3

Input

1

Expected output

1

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

Find divisor pairs up to the square root, avoiding a duplicate for a perfect square. Sort the collected divisors. Time: O(√n + k log k), space: O(k), for k divisors.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ArrayList<Long> values = new ArrayList<>();
        while (in.hasNextLong()) values.add(in.nextLong());
        long[] a = values.stream().mapToLong(Long::longValue).toArray();
        long n = a[0];
        ArrayList<Long> result = new ArrayList<>(); for (long i = 1; i <= n / i; i++) if (n % i == 0) { result.add(i); if (i != n / i) result.add(n / i); } Collections.sort(result); for (long v : result) System.out.print(v + " ");
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.