常用的算法:穷举,迭代

来源:互联网 发布:php关闭notice警告 编辑:程序博客网 时间:2024/06/07 02:09

穷举:

*在有限的范围内,可以对所有的值都进行试验和判断从而满足条件的值

*穷举的基本模式
for (;;){ if(); }

例如:

计算水仙花数:

public class All_1{    public static void main(String args[]){        for( int a =1;a=9;a++)            for( int b =0; b<=9;b++)                for(int c=0; c<=9;c++)                    if( a*a*a+b*b*b+c*c*c == 100*a+10*b +c)                        System.out.println(100*a+10*b+c);    }}

计算完全数:

class All_2{    public static void main(String[] args){        for( int n=1 ;n<9999;n++)            if(n==divsum(n) ) System.out.println(n);    }    public static int divsum(int n){        int s = 0;        for(int i = 1; i<n;i++)            if(n%i == 0) s+=i;        return s;    }}

迭代:

*是多次利用同一个公式进行计算,每次将计算的结果在带入公式进行计算,从而逐步逼近精确解

*迭代的基本模式:

while() { x = f(x);}

例如:

计算平方根:

public class Sqrt{    public static void main(String args[]){        System.out.println(sqrt(98.0));        System.out.println(Math.sqrt(98.0));    }    static double sqrt(double a){        double x =1.0;        do{            x = (x +a/x)/2;            System.out.println(x + "," + a/x);        }while(Math.abs(x*x-a)/a >1e-6);        return x;    }}


原创粉丝点击