public class DiGui {
    
    /** Creates a new instance of DiGui */
    long result,a=100;
    public static void main(String args[])
    {
        DiGui dg=new DiGui();
        dg.getResult(1,2);
      
    }
    public void getResult(long i,long j)
    {
         result=i+j;
         System.out.println(result);
         i=j;
         j=result;
         a--;
         if(a>0)
         getResult(i,j);
         
    }
}
//我用它解决菲菠那契数列(前100项),但打印的结果有负数,我想是结果已超出了long型所能表示的范围,除此之外我还想请教一些经典算法

解决方案 »

  1.   

    public static void f() {
         long temp1 = 1;
         System.out.println(temp1);
         long temp2 = 1;
         System.out.println(temp2);
         long temp3;
         for(int i=2; i<100; i++) {
         temp3 = temp1 + temp2;
         System.out.println(temp3);
         temp1 = temp2;
         temp2 = temp3;
         }
        }
      

  2.   

    来一个0,1背包的
    package sunflowerbbs.oicp.net;public class ZeroOneBeiBao {
        /**
         * 
         * @param w
         * @param sum
         * @param n: n<=w.length-1;
         * @return 返回数组w中的一个或多个(不超过n)之和能否为sum
         */
    static boolean knap(int[] w, int sum, int n) {
    if (sum == 0)
    return true;
    if (sum < 0 || (sum > 0 && n < 0) )
    return false;
    if (knap(w, sum - w[n], n - 1)) {
    System.out.println(w[n] + ",");
    return true;
    }
    return knap(w, sum, n - 1);
    }
    public static void main(String[] args) {
    int W[] = { 1, 5, 7, 8,10,15 };
    //看看数组中的元素之和能不能为45
    System.out.println(knap(W, 27,W.length-1));
    }}