Skip to content

Commit b968af3

Browse files
committed
Divisors of Given N
1 parent 23a797b commit b968af3

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.java.basic;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.Scanner;
6+
7+
/*
8+
* Divisors of N
9+
*
10+
* This program finds all the divisors of the
11+
* Given number N
12+
*
13+
* say Given Number is 45, Divisors are
14+
* [1, 3, 5, 9, 15, 45]
15+
*
16+
* say Given Number is 60, Divisors are
17+
* [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60]
18+
*
19+
*/
20+
21+
public class Divisors {
22+
23+
public static void main(String[] args) {
24+
Scanner scanner = new Scanner(System.in);
25+
System.out.println("Enter the N value : ");
26+
int N = Integer.parseInt(scanner.nextLine().trim());
27+
28+
ArrayList<Integer> divisors = new ArrayList<>();
29+
for(int i=1;i<N;i++){
30+
int d = N % i;
31+
if(d == 0){
32+
//say n is 10
33+
//if 10 is divide by 2
34+
//then it will be divide by 5
35+
//10%2 == 0 also 10/2 == 0 (5)
36+
divisors.add(i);
37+
divisors.add(N/i);
38+
}
39+
if(N/i <= i)
40+
break;
41+
}
42+
Collections.sort(divisors);
43+
System.out.println("The divisors of "+N+" are : "+divisors.toString() );
44+
System.out.println("Number of Divisors are : "+divisors.size());
45+
scanner.close();
46+
}
47+
}
48+
/*
49+
Enter the N value : 45
50+
The divisors of 45 are :
51+
[1, 3, 5, 9, 15, 45]
52+
Number of Divisors are : 6
53+
54+
Enter the N value : 60
55+
The divisors of 60 are :
56+
[1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60]
57+
Number of Divisors are : 12
58+
*/

0 commit comments

Comments
 (0)