Question:
Java code to find the divisors of a given number? such as: entering six, and getting 1,2,3,6 as output?
Code:
import java.util.Scanner; public class Divisors { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter number: "); int n = sc.nextInt();; System.out.print(1); for (int i = 2; i <= n; i++) { if (n % i == 0) { System.out.print("," + i); } } System.out.println(); } }
Output:
$ java Divisors Enter number: 6 1,2,3,6