public class Factors {
private boolean[] factors;
private int value;
public Factors(int value) {
this.value = value;
factors = new boolean[value + 1];
}
public void calculateFactors() {
for (int i = 1; i < factors.length; i++) {
factors[i] = value % i == 0;
}
}
public void printFactors() {
for (int i = 1; i < factors.length; i++) {
System.out.print(factors[i] ? i + " " : "");
}
System.out.println();
}
public boolean isPerfect() {
int count = 0;
for (int i = 1; i < factors.length; i++) {
count += factors[i] ? 1 : 0;
}
return count == 2;
}
public void printCommonFactors(Factors other) {
for (int i = 0; i < Math.min(other.factors.length, factors.length); i++) {
System.out.print(factors[i] && other.factors[i] ? i + " " : "");
}
System.out.println();
}
public void printUnique(Factors other) {
for (int i = 0; i < Math.max(other.factors.length, factors.length); i++) {
if (i < other.factors.length && i < factors.length) {
System.out.print(factors[i] ^ other.factors[i] ? i + " " : "");
} else if (i < other.factors.length) {
System.out.print(other.factors[i] ? i + " " : "");
} else {
System.out.print(factors[i] ? i + " " : "");
}
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Factors a = new Factors(28);
a.calculateFactors();
Factors b = new Factors(42);
b.calculateFactors();
System.out.println("All:");
System.out.println("a:");
a.printFactors();
System.out.println("b:");
b.printFactors();
System.out.println("Unique");
a.printUnique(b);
System.out.println("Common:");
a.printCommonFactors(b);
System.out.println("Is a perfect: " + a.isPerfect());
System.out.println("Is b perfect: " + b.isPerfect());
}
}
Comments
Leave a comment