Program::
对一个正整数分解质因数
代码如下:
1 package test; 2 3 import java.util.Scanner; 4 5 6 public class TestDemo { 7 8 public static void main(String args[]) { 9 10 int num = 0; 11 Scanner scan = new Scanner(System.in); 12 13 System.out.println( "请输入一个正整数:" ); 14 num = scan.nextInt(); 15 16 display(num); 17 } 18 19 20 /* 21 * 将一个整数分解质因数 22 * */ 23 public static void display(int num) { 24 25 int temp = 2; //从2开始 26 27 System.out.print( num + "=" ); 28 29 while( num != 1 ) { //当num的值为1时结束 30 31 if( num == temp ) { //相等时,将num置1结束循环 32 33 System.out.print( temp + "*" ); 34 num = 1; 35 }else if( num % temp == 0 ) { //num能够被temp整除,则改变num的值 36 37 num = num / temp; 38 System.out.print( temp + "*" ); 39 }else { //不能整除时,temp值加1 40 41 temp += 1; 42 } 43 44 45 } 46 } 47 48 }