This commit is contained in:
Kizuren 2025-09-17 21:45:48 +02:00
parent fa218ada23
commit daddc3779a
3 changed files with 64 additions and 0 deletions

3
.gitignore vendored
View file

@ -22,3 +22,6 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
replay_pid* replay_pid*
# IntelliJ IDEA
.idea

11
gcd.iml Normal file
View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

50
src/Main.java Normal file
View file

@ -0,0 +1,50 @@
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int a = 48;
int b = 18;
int normalResult = normalGcd(a, b);
int euclideanResult = euclideanGcd(a, b);
System.out.printf("Normal gcd: %d%n", normalResult);
System.out.printf("Euclidean gcd: %d%n", euclideanResult);
}
public static int normalGcd(int a, int b) {
List<Integer> factorsA = primeFactors(a);
List<Integer> factorsB = primeFactors(b);
int gcd = 1;
for (int i = 0; i < factorsA.size(); i++) {
int factor = factorsA.get(i);
if (factorsB.contains(factor)) {
gcd *= factor;
factorsB.remove((Integer) factor);
}
}
return gcd;
}
private static List<Integer> primeFactors(int n) {
List<Integer> factors = new ArrayList<>();
for (int i = 2; i * i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) factors.add(n);
return factors;
}
public static int euclideanGcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}