日期:2014-05-20 浏览次数:20949 次
public class Program4 {
static StringBuffer str = new StringBuffer();
public static void main(String[] args) {
System.out.print(test(90));
}
public static String test(int n) {
str = str.append(n+ " = 1");
if(n <= 3) {
System.out.print("请输入一个大于3的正整数!");
System.exit(1);
}
for(int i = 2; i <= n; i++) {
if(n%i == 0) {
str = str.append("*" +i);
n = n/i;
return test1(n);
}
}
return " errer";
}
public static String test1(int n) {
for(int i = 2; i <= n; i++) {
if(n%i == 0) {
str = str.append("*" +i);
n = n/i;
if(n == 1) {
return str.toString();
}
return test1(n);
}
}
return "err";
}
}
public class Program4 {
static StringBuffer str = new StringBuffer();
private static boolean first = true;
public static void main(String[] args) {
System.out.print(test(90));
}
public static String test(int n) {
if (first) {
str = str.append(n + " = 1 ");
if (n <= 3) {
System.out.print("请输入一个大于3的正整数!");
System.exit(1);
}
}
first = false;
if (n == 1)
return str.toString();
for (int i = 2; i <= n; i++) {
if (n % i == 0) {
str = str.append("* " + i);
n = n / i;
return test(n);
}
}
return " errer";
}
}
------解决方案--------------------
public class Program4 {
static StringBuffer str = new StringBuffer();
public static void main(String[] args) {
System.out.print(test2(200));
}
public static String test(int n) {
str = str.append(n+ " = 1");
if(n <= 3) {
System.out.print("请输入一个大于3的正整数!");
System.exit(1);
}
for(int i = 2; i <= n; i++) {
if(n%i == 0) {
str = str.append("*" +i);
n = n/i;
return test1(n);
}
}
return " errer";
}
public static String test1(int n) {
for(int i = 2; i <= n; i++) {
if(n%i == 0) {
str = str.append("*" +i);
n = n/i;
if(n == 1) {
return str.toString();
}
return test1(n);
}
}
return "err";
}
//下面的test2不用递归:
//
public static String test2(int n){
if(n<=3){
System.out.print("请输入一个大于3的正整数!");
System.exit(1);
}
str.append(n+" = 1");
int x=n;
int i=2;
while(x!=1){
if(x%i==0){
str.append("*"+i);
x/=i;
}else{
i++;
}
}
return str.toString();
}
}