前段时间做了一道算法题,如下:
【题目描述】
一个大于2的整数N,他可能等于比它小的若干个整数(大于等于2并且不等于自己)乘积。如果存在这样的连续整数,将他们输出,如果没有则输出-1。
例: 整数60,60=3*4*5,所以输出[3 4 5]。
计算结果按行输出至本地文件,输出顺序按照参数读入的顺序输出。
【输入文件内容样例】
120
139708800
914848764359059584
2032957340612951426
57274321104000
……
【输出文件内容样例】
[2 3 4 5],[4 5 6]
-1
-1
-1
[49 50 51 52 53 54 55 56]
……
我的解答如下,可供参考:
private String dealBiz(String infilename) throws Exception {
int index = infilename.lastIndexOf(File.separator);
String path = infilename.substring(0, index);
String retfullfile = path + File.separator + "out.txt"; // 最终生成的结果文件路径
List<String> writeout = new ArrayList<String>();
InputStreamReader read = new InputStreamReader(new FileInputStream(infilename));
BufferedReader bufferedReader = new BufferedReader(read);
String linestr = null;
while ((linestr = bufferedReader.readLine()) != null) {
if (linestr.length() > 1) {
String lineresule = "";
long line = 0;
try {
line = Long.parseLong(linestr);
} catch (Exception e) {
writeout.add("-1");
continue;
}
long times = (long) Math.sqrt(line); // 最大循环次数只要开平方根取整次即可
long succ = 0;
for (long i = 2; i <= times; i++) {
long templine = line;
long tempi = i;
String canuse = "[";
boolean isgo = true;
while (isgo) {
isgo = isgo(templine, tempi);
if (isgo) {
canuse = canuse + tempi + " ";
if (templine / tempi == 1) {
canuse = canuse + "]";
lineresule = lineresule + canuse + ",";
succ++;
break;
}
templine = templine / tempi;
tempi = tempi + 1;
}
}
}
if (succ == 0) {
lineresule = "-1";
}
int index2 = lineresule.lastIndexOf(",");
if (index2 > 0) {
lineresule = lineresule.substring(0, index2);
}
writeout.add(lineresule);
} else {
break;
}
}
read.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(retfullfile)));
int size = writeout.size();
for (int i = 0; i < size; i++) {
String line = writeout.get(i) + "\r\n";
bw.write(line);
}
bw.close();
return retfullfile;
}
public boolean isgo(long line, long i) {
if (line % i == 0) {
return true;
}
return false;
}