题目描述
当你学一些可视化程序设计语言时,老师经常会让你设计并且编程做出一个计算器,这时也许你会仿照windows系统自带的计算器外观和功能去设计,但是现在老师要你多做出一个有新功能的计算器,实现当输入一个数时,能够将这个数分解成一个或多个素因子乘积的形式,并按素因子的大小排列显示出来。大家对计算器中数的表示应该很清楚的。下面显示出了0 — 9这十个数字的表示形式。每个数字都占据5 * 3大小的字符区域
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n;
boolean[] isPrime;
List<Integer> list;
while(scanner.hasNext()){
n=scanner.nextInt();
list=new ArrayList<Integer>();
isPrime=checkPrime(n);
int temp=n;
if(!isPrime[n]){ //n不是质数
for(int i=2;i<=n;i++){
if(isPrime[i]){ //分解因数
while(temp%i==0){
list.add(i);
temp=temp/i;
}
if(temp==1){ //质数分解已经完成
break;
}
}
}
}else{ //n是质数
list.add(n);
}
print(list);
}
}
public static boolean[] checkPrime(int n){ //筛选法求素数
boolean[] isPrime=new boolean[n+1];
for(int i=3;i<=n;i=i+2){
isPrime[i]=true;
}
for(int i=3;i<n;i=i+2){
if(isPrime[i]){
for(int j=i+i;j<=n;j=j+i){
isPrime[j]=false;
}
}
}
if(n>1){
isPrime[2]=true;
}
return isPrime;
}
//输出字符串
public static void print(List<Integer> list){
String[][] chars= { {" - ","| |"," ","| |"," - "},
{" "," |"," "," |"," "},
{" - "," |"," - ","| "," - "},
{" - "," |"," - "," |"," - "},
{" ","| |"," - "," |"," "},
{" - ","| "," - "," |"," - "},
{" - ","| "," - ","| |"," - "},
{" - "," |"," "," |"," "},
{" - ","| |"," - ","| |"," - "},
{" - ","| |"," - "," |"," - "}
};
String temp;
String[] str;
int num;
int size=list.size();
StringBuilder[] lines=new StringBuilder[5];
for(int i=0;i<5;i++){
lines[i]=new StringBuilder();
}
for(int i=0;i<size;i++){
temp=Integer.toString(list.get(i));
for(int j=0;j<temp.length();j++){
num=temp.charAt(j)-'0';
str=chars[num];
for(int k=0;k<5;k++){
lines[k].append(str[k]);
}
}
if(i!=size-1){
for(int k=0;k<5;k++){
if(k!=2){
lines[k].append(" ");
}else{
lines[k].append("*");
}
}
}
}
for(int i=0;i<5;i++){
System.out.println(lines[i].toString());
}
}
}