程序分析:對n進行分解質因數,應先找到一個最小的質數k,然后按下述步驟完成:
1、如果這個質數恰等于n,則說明分解質因數的過程已經結束,打印出即可。
2、如果n <> k,但n能被k整除,則應打印出k的值,并用n除以k的商,作為新的正整數你,重復執行第一步。
3、如果n不能被k整除,則用k+1作為k的值,重復執行第一步。
程序設計:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class exp2{ public exp2(){} public void fengjie( int n){ for ( int i= 2 ;i<=n/ 2 ;i++){ if (n%i== 0 ){ System.out.print(i+ "*" ); fengjie(n/i); } } System.out.print(n); System.exit( 0 ); ///不能少這句,否則結果會出錯 } public static void main(String[] args){ String str= "" ; exp2 c= new exp2(); str=javax.swing.JOptionPane.showInputDialog( "請輸入N的值(輸入exit退出):" ); int N; N= 0 ; try { N=Integer.parseInt(str); } catch (NumberFormatException e){ e.printStackTrace(); } System.out.print(N+ "分解質因數:" +N+ "=" ); c.fengjie(N); } } |