Scanner sc = new Scanner(System.in); while (sc.hasNext()) { long num = sc.nextLong(); for (long i = 2; i <= (long) Math.sqrt(num); i++) { while (num % i == 0) { System.out.print(i + " "); num /= i; } } if (num > 2) { System.out.print(num); } }