【因子演算法】——求一個數的因子、質因子、求兩個數的公因子
阿新 • • 發佈:2019-02-02
下面理清楚一些數學概念:
因數:一個數,如果存在可以被它整除的數,則這些數都是該數的因數。
規定0沒有因數,1的因數是1,其他的比如4的因數有“1”、“2”、“4
因子:一個數,如果存在可以被它整除的數且這些數不包括它本身,則這些書都是該數的因子。
規定0沒有因子,1的因子是1,其他的比如4的因子有“1”、“2”
質因子:一個數,如果可以分解成n個質數相乘,則n個質數成為該數的質因子。
規定0和1沒有質因子,質數的質因子為其本身
完數:一個數的因子之和等於它本身,則該數為完數。
場景一:輸入有一個自然數n,輸出其所有的因子,並返回因子的個數(這裡通常指的是正因子)。
思路:如果是0,則返回0;如果是1,則返回1,如果是2,則返回2;如果大於2,則從2到根號n依次判斷取餘即可
程式碼實現(java)
/** * 求一個數的因子,這裡值的是正因子,包含1,但不包含本身。 * @param n 自然數 * @return 因子的個數 */ public static int getFactors(int n){ int count = 0; if(n == 0) return count; else if(n == 1 || n == 2){ System.out.println("n"); return ++count; } else{ //包含1 System.out.print(1+" "); int l = (int) Math.sqrt(n); for(int i = 2; i <= l; i++){ if(n % i == 0){ System.out.print(i+" "); System.out.print(n/i+" "); count += 2; } } } return count+1; }
場景二:輸入有一個自然數n,輸出其所有的質因子,並返回質因子的個數。
思路: 如果是0或者1,則返回0;否則,則先判斷是否為質數,如果不是,用一個cur變數儲存“能被整除的質數”,先賦值為2.,依次從cur開始做取餘操作,如果不為0則cur遞增取下一個質數,直到餘數為0,cur儲存當前質數,n儲存為n/cur,直到為質數為止。
程式碼實現(java)
測試資料列印如下/** * 求一個自然數的質因子 * @param n 自然數 * @return 質因子個數 */ public static int getFactorsByPrimeNumber(int n){ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(2); int m = n; if(n == 0 || n ==1) return 0; else{ if(Day1.isPrimeNumber(m)){ list.add(n); System.out.print(n+"= 1*"+n); return 1; }else{ int curLast = 0; while(!Day1.isPrimeNumber(m)){ curLast = list.getLast(); while(true){ if(Day1.isPrimeNumber(curLast)){ if(m % curLast == 0){ list.add(curLast); m = m / curLast; break; } } curLast++; } } list.add(m); //列印輸出 int valuse = list.get(1); int count = 1; System.out.print(n+"="+valuse); for(int i = 2; i < list.size(); i++){ System.out.print("*"+list.get(i)); if(valuse != list.get(i)){ count++; valuse = list.get(i); } } return count; } } }
40=2*2*2*5 40的質因子一共有2個
96=2*2*2*2*2*3 96的質因子一共有2個
157= 1*157 157的質因子一共有1個
場景三:輸入兩個數n和m,輸出n和m的公因子,並返回公因子個數,
思路: 兩個數的公因子包含必定是兩個數的最大公約數的因子,如果最大公約數為n或者m,則公因子還包括最大公約數本身。
程式碼實現(java)
/**
* 求兩個數的公因子
* 思路:
* 1. 先求兩個數的公約數
* 2. 對最大公約數進行求因子。如果該公約數為所求兩個數較小的數,則公因子不包括該數,否則則包括
* 比如 30 15 最大公約數為15 公因子為 1 3 5
* 比如 20 8 最大公約數為4 公因子為 1 2 4
* @param n m 引數
* @return 公因子個數
*/
public static int getAllFactors(int n,int m){
int count = 0;
if(n ==0 || m ==0)
return 0;
else{
//呼叫最大公約數函式
int greatestCommonMeasure = Tools.getGreatestCommonMeasure_2(n, m);
if(greatestCommonMeasure == 0){
return greatestCommonMeasure;
}else if(greatestCommonMeasure == 1){
System.out.println(1+" ");
return greatestCommonMeasure;
}else{
System.out.print(1+" ");
count++;
if(greatestCommonMeasure != n && greatestCommonMeasure != m){
count++;
System.out.print(greatestCommonMeasure+" ");
}
int l = (int) Math.sqrt(greatestCommonMeasure);
for(int i = 2; i <= l; i++){
if(greatestCommonMeasure % i == 0){
System.out.print(i+" ");
System.out.print(greatestCommonMeasure/i+" ");
count += 2;
}
}
}
return count;
}
}