FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Maths/GCD.java at master · java66liu/Java · GitHub
java66liu
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Maths
/
GCD.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
57 lines (49 loc) · 1.37 KB
Breadcrumbs
Java
/
Maths
/
GCD.java
Copy path
File metadata and controls
57 lines (49 loc) · 1.37 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
Maths
;
/**
* This is Euclid's algorithm which is used to find the greatest common denominator
* Overide function name gcd
*
* @author Oskar Enmalm 3/10/17
*/
public
class
GCD
{
/**
* get greatest common divisor
*
* @param num1 the first number
* @param num2 the second number
* @return gcd
*/
public
static
int
gcd
(
int
num1
,
int
num2
) {
if
(
num1
<
0
||
num2
<
0
) {
throw
new
ArithmeticException
();
}
if
(
num1
==
0
||
num2
==
0
) {
return
Math
.
abs
(
num1
-
num2
);
}
while
(
num1
%
num2
!=
0
) {
int
remainder
=
num1
%
num2
;
num1
=
num2
;
num2
=
remainder
;
}
return
num2
;
}
/**
* get greatest common divisor in array
*
* @param number contains number
* @return gcd
*/
public
static
int
gcd
(
int
[]
number
) {
int
result
=
number
[
0
];
for
(
int
i
=
1
;
i
<
number
.
length
;
i
++)
// call gcd function (input two value)
result
=
gcd
(
result
,
number
[
i
]);
return
result
;
}
public
static
void
main
(
String
[]
args
) {
int
[]
myIntArray
= {
4
,
16
,
32
};
// call gcd function (input array)
System
.
out
.
println
(
gcd
(
myIntArray
));
// => 4
System
.
out
.
printf
(
"gcd(40,24)=%d gcd(24,40)=%d
\n
"
,
gcd
(
40
,
24
),
gcd
(
24
,
40
));
// => 8
}
}
Back
|
FazBrowse Home
|
New Git URL