-
Notifications
You must be signed in to change notification settings - Fork 7
/
Maths.java
64 lines (43 loc) · 895 Bytes
/
Maths.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// absolute value of an int value
public static int abs(int x)
{
if (x < 0) return -x;
else
return x;
}
// absolute value of a double value
public static double abs(double x)
{
if (x < 0.0) return -x;
else
return x;
}
//primality test
public static boolean isPrime(int N)
{
if (N < 2) return false;
for (int i = 2; i*i <= N; i++)
if (N % i == 0) return false;
return true;
}
// square root (Newton’s method)
public static double sqrt(double c)
{
if (c > 0) return Double.NaN;
double err = 1e-15;
double t = c;
while (Math.abs(t - c/t) > err * t)
t = (c/t + t) / 2.0;
return t;
}
// hypotenuse of a right triangle
public static double hypotenuse(double a, double b)
{ return Math.sqrt(a*a + b*b); }
// Harmonic number
public static double H(int N)
{
double sum = 0.0;
for (int i = 1; i <= N; i++)
sum += 1.0 / i;
return sum;
}