This is the code for evaluating factors of given integer array. The problem is I need to find LCM from the list I have received as output. Suggest something for removing duplicate elements from list
Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int [] ar = {6,12,36};
for (int a:
ar) {
System.out.println(getFactor(a));
}
getFactor(long) returns the list of factors
private static List<Integer> getFactor(long n) {
List<Integer> l = new ArrayList<>();
for (int i=2;n!=1;i++)
{
if(n%i==0)
{
l.add(i);
n=n/i;
i=1;
}
}
return l;
}
/*Input
6,12,36
Output
[2, 3]
[2, 2, 3]
[2, 2, 3, 3]*/
Problem remove the [2,3] duplicates from other lists to get LCM(Least Common Multiple).
No where in your code you're calculating the lcm. All I see is you have found the factors of three numbers.
[2, 3] -> Factors of 6
[2, 2, 3] -> Factors of 12
[2, 2, 3, 3] -> -> Factors of 6
You'll have to write another function to calculate the lcm.
Suggest something for removing duplicate elements from list
Use Set
instead of a List
private static Set<Integer> getFactor(long n) {
Set<Integer> l = new HashSet<>();
for (int i = 2; n != 1; i++) {
if (n % i == 0) {
l.add(i);
n = n / i;
i = 1;
}
}
return l;
}
Output:
[2, 3]
[2, 3]
[2, 3]
Recommended reading: What is the difference between Set and List?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.