程序分析:對(duì)n進(jìn)行分解質(zhì)因數(shù),應(yīng)先找到一個(gè)最小的質(zhì)數(shù)k,然后按下述步驟完成:
1、如果這個(gè)質(zhì)數(shù)恰等于n,則說(shuō)明分解質(zhì)因數(shù)的過(guò)程已經(jīng)結(jié)束,打印出即可。
2、如果n <> k,但n能被k整除,則應(yīng)打印出k的值,并用n除以k的商,作為新的正整數(shù)你,重復(fù)執(zhí)行第一步。
3、如果n不能被k整除,則用k+1作為k的值,重復(fù)執(zhí)行第一步。
程序設(shè)計(jì):
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 ); ///不能少這句,否則結(jié)果會(huì)出錯(cuò) } public static void main(String[] args){ String str= "" ; exp2 c= new exp2(); str=javax.swing.JOptionPane.showInputDialog( "請(qǐng)輸入N的值(輸入exit退出):" ); int N; N= 0 ; try { N=Integer.parseInt(str); } catch (NumberFormatException e){ e.printStackTrace(); } System.out.print(N+ "分解質(zhì)因數(shù):" +N+ "=" ); c.fengjie(N); } } |