File tree 1 file changed +50
-0
lines changed
1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .kunal .maths ;
2
+
3
+ import java .util .ArrayList ;
4
+
5
+ public class Factors {
6
+ public static void main (String [] args ) {
7
+ factors3 (20 );
8
+ }
9
+
10
+ // O(n)
11
+ static void factors1 (int n ) {
12
+ for (int i = 1 ; i <= n ; i ++) {
13
+ if (n % i == 0 ) {
14
+ System .out .print (i + " " );
15
+ }
16
+ }
17
+ }
18
+
19
+ // O(sqrt(n))
20
+ static void factors2 (int n ) {
21
+ for (int i = 1 ; i <= Math .sqrt (n ); i ++) {
22
+ if (n % i == 0 ) {
23
+ if (n /i == i ) {
24
+ System .out .print (i + " " );
25
+ }else {
26
+ System .out .print (i + " " + n /i + " " );
27
+ }
28
+ }
29
+ }
30
+ }
31
+
32
+ // both time and space with be O(sqrt(n))
33
+ static void factors3 (int n ) {
34
+ ArrayList <Integer > list = new ArrayList <>();
35
+ for (int i = 1 ; i <= Math .sqrt (n ); i ++) {
36
+ if (n % i == 0 ) {
37
+ if (n /i == i ) {
38
+ System .out .print (i + " " );
39
+ }else {
40
+ System .out .print (i + " " );
41
+ list .add (n /i );
42
+ }
43
+ }
44
+ }
45
+ for (int i = list .size () - 1 ; i >= 0 ; i --) {
46
+ System .out .print (list .get (i ) + " " );
47
+ }
48
+ }
49
+
50
+ }
You can’t perform that action at this time.
0 commit comments