算法練習普通(分解質因數)

神龜雖壽,猶有竟時。
點贊再看,養成習慣。

在這裏插入圖片描述
問題描述
  求出區間[a,b]中所有整數的質因數分解。

輸入格式
  輸入兩個整數a,b。

輸出格式
  每行輸出一個數的分解,形如k=a1a2a3…(a1<=a2<=a3…,k也是從小到大的)(具體可看樣例)

樣例輸入
3 10

樣例輸出
3 = 3
4 = 2 * 2
5 = 5
6 = 2* 3
7 = 7
8 = 2 * 2 * 2
9 = 3 * 3
10 = 2 * 5

提示
  先篩出所有素數,然後再分解。
數據規模和約定
  2<=a<=b<=10000

import java.util.Scanner;

public class 分解質因數 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
 
		for (int i = a; i <= b; i++) {
			hu(i);			// 調用分解質因數的函數
		}
	}
 
	public static void hu(int x) {
		int s = 2;
		int a = x;
		int c = 1;
		while (s <= a) {
			if (x % s != 0) {
				s++;
			} else {
				x /= s;
				if (c == 1) {
					System.out.print(a + "=" + s);
					c++;
				} else {
					System.out.print("*" + s);
				}
			}
		}
		System.out.println();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章