Skip to content

Commit cadb741

Browse files
committed
MathLib.gcd/lcm/divisors
1 parent dbad12f commit cadb741

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

Math/MathLib.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ private static long[] inv_gcd(long a, long b){
2222
return new long[]{s,m0};
2323
}
2424

25+
public static long gcd(long a, long b){
26+
a = java.lang.Math.abs(a);
27+
b = java.lang.Math.abs(b);
28+
return inv_gcd(a, b)[0];
29+
}
30+
public static long lcm(long a, long b){
31+
a = java.lang.Math.abs(a);
32+
b = java.lang.Math.abs(b);
33+
return a / gcd(a,b) * b;
34+
}
35+
2536
public static long pow_mod(long x, long n, int m){
2637
assert n >= 0;
2738
assert m >= 1;
@@ -86,4 +97,18 @@ public static long floor_sum(long n, long m, long a, long b){
8697
ans += floor_sum(y_max, a, m, (a-x_max%a)%a);
8798
return ans;
8899
}
100+
101+
public static java.util.ArrayList<Long> divisors(long n){
102+
java.util.ArrayList<Long> divisors = new ArrayList<>();
103+
java.util.ArrayList<Long> large = new ArrayList<>();
104+
105+
for(long i=1; i*i<=n; i++) if(n%i==0){
106+
divisors.add(i);
107+
if(i*i<n) large.add(n/i);
108+
}
109+
for(int p=large.size()-1; p>=0; p--){
110+
divisors.add(large.get(p));
111+
}
112+
return divisors;
113+
}
89114
}

Math/README.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,18 @@ $$ x \equiv r[i] \mod m[i] $$ を解きます.
2121
public static long floor_sum(long n, long m, long a, long b)
2222
```
2323

24-
$ \sigma_{i=0}^{n-1} floor(\frac{a*i+b}{m}) $を返します.
24+
$ \sigma_{i=0}^{n-1} floor(\frac{a*i+b}{m}) $を返します.
25+
26+
## gcd, lcm
27+
28+
```java
29+
public static long gcd(long a, long b)
30+
public static long lcm(long a, long b)
31+
```
32+
二整数 a, b の最大公約数/最小公倍数を返します. 返り値は必ず非負整数になります.
33+
34+
```java
35+
public static java.util.ArrayList<Long> divisors(int n)
36+
```
37+
整数nの約数を昇順に含んだリストを返します.
38+
計算量: O(√n)

0 commit comments

Comments
 (0)