我試圖構建一個用於查找'N'數字LCM的Java程序。但首先我堅持要找出一個數字的總素數,包括它們的出現次數。例如(6 = 2×3)和(8 = 2×2×2)。但是我得到的輸出是(6)的'2'和(8)的兩個'2'。對方在哪裏?我甚至會檢查整數'是否爲素數。找到主要因素,包括它們的總髮生次數(Java)
package lcm;
import java.util.ArrayList;
import java.util.Scanner;
public class LCM {
public static boolean isPrime(int numero){
for (int i = 2; i <= Math.sqrt(numero); i++) {
if (numero % i == 0) {
return false;
}
}
return true;
}
public static void factor(int x){
int s;
int copy = x;
ArrayList<Integer> al = new ArrayList<>();
for(s=2;s<copy;s++){
if(copy%s==0){
if (isPrime(s)){
al.add(s);
copy/=s;
//used for repetition
s--;
}
}
}
for(int p : al){
System.out.println(p);
}
}
public static void main(String[] args) {
// TODO code application logic here
int j,k;
int temp=0;
System.out.println("Enter no. of numbers");
Scanner cin = new Scanner(System.in);
int i = cin.nextInt();
int []a = new int[i];
int []b=new int[100];
System.out.println("Enter numbers one by one");
for(j=0;j<a.length;j++){
a[j] = cin.nextInt();
}
for(j=0;j<a.length;j++){
temp=a[j];
factor(temp);
}
}
}
原因是當s = 2和複製也當時它跳過變爲2的情況下該循環只顯示了兩個2。嘗試把<=複製在那個地方@kevin Souza –
:)。非常感謝。 –
還有一個更好的方法:'LCM(a,b)= | a.b |/GCD(a,b)'...並使用Euclid算法計算GCD。 –