一道简单的编程题启示

本文通过两段程序对比展示了寻找第一个因数个数超过500的三角数的过程。第一段程序虽然实现了目标但效率低下,耗时长达3605毫秒;而第二段程序则通过优化算法显著提高了效率,仅耗时25毫秒。本文旨在说明算法优化的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自认为作为程序员来说,对语言的掌握是必须的,然而更重要的是算法。
以下两个程序都是实现一个问题,思路大致相似,然结果却天差地别。这也许给我们编程以启示。
题目:
我们称由自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");
 }
 
}
 
程序一结果:
76576500
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");
    }
 
}
程序二结果:
12375 76576500 Time: 25ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值