自认为作为程序员来说,对语言的掌握是必须的,然而更重要的是算法。
以下两个程序都是实现一个问题,思路大致相似,然结果却天差地别。这也许给我们编程以启示。
题目:
我们称由自1到n的连续自然数之和为三角数。如第七个三角数为:1+2+3+4+5+6+7=28;
现在我们要求第一个因数个数大于500的三角数(即该三角数最小)。
程序一:
public class P12 {
public static void main(String args[]){
int start = 250,count = 0;
long result;
long beg = System.currentTimeMillis();
while(true){
result = start * (start + 1)/2;
for(int i =1;i <Math.sqrt(result)+1 + 1;i++ ){
if(result % i == 0)
count ++;
}
if(count>=250)
break;
else{
start ++;
count = 0;
}
}
System.out.println(result);
long end = System.currentTimeMillis();
System.out.println((end - beg)+"ms");
}
}
public static void main(String args[]){
int start = 250,count = 0;
long result;
long beg = System.currentTimeMillis();
while(true){
result = start * (start + 1)/2;
for(int i =1;i <Math.sqrt(result)+1 + 1;i++ ){
if(result % i == 0)
count ++;
}
if(count>=250)
break;
else{
start ++;
count = 0;
}
}
System.out.println(result);
long end = System.currentTimeMillis();
System.out.println((end - beg)+"ms");
}
}
程序一结果:
76576500
3605ms
3605ms
程序二:
public class P12 {
/** Creates a new instance of FactorCount */
public P12(int limit) {
int cnt = 0;
for (int i = 1; cnt <= limit; i++){
if (i % 2 == 0) cnt = count(i / 2) * count (i+1);
else cnt = count(i) * count((i+1)/2);
// System.out.println("" + i + "\t" + cnt);
if (cnt > 500)
answer = i;
}
}
int answer = 0;
int count(int n) {
int result = 0;
for (int i = 1; i*i <= n; i++){
if (n % i == 0) {
result+=2;
if (n / i == i)
result--;
}
}
return result;
}
int getAnswer(){return answer;}
public static void main(String[] args){
long start = System.currentTimeMillis();
int n = new P12(500).getAnswer();
long stop = System.currentTimeMillis();
System.out.println("" + n + "\t"+ n*(n+1)/2 + "\tTime: " + (stop-start) + "ms");
}
}
public class P12 {
/** Creates a new instance of FactorCount */
public P12(int limit) {
int cnt = 0;
for (int i = 1; cnt <= limit; i++){
if (i % 2 == 0) cnt = count(i / 2) * count (i+1);
else cnt = count(i) * count((i+1)/2);
// System.out.println("" + i + "\t" + cnt);
if (cnt > 500)
answer = i;
}
}
int answer = 0;
int count(int n) {
int result = 0;
for (int i = 1; i*i <= n; i++){
if (n % i == 0) {
result+=2;
if (n / i == i)
result--;
}
}
return result;
}
int getAnswer(){return answer;}
public static void main(String[] args){
long start = System.currentTimeMillis();
int n = new P12(500).getAnswer();
long stop = System.currentTimeMillis();
System.out.println("" + n + "\t"+ n*(n+1)/2 + "\tTime: " + (stop-start) + "ms");
}
}
程序二结果:
12375 76576500 Time: 25ms