java之数学方法

参考http://how2j.cn/k/number-string/number-string-math/319.html

java.lang.Math提供了一些常用的数学运算方法,并且都是以静态方法的形式存在

四舍五入, 随机数,开方,次方,π,自然常数

package digit;
  
public class TestNumber {
  
    public static void main(String[] args) {
        float f1 = 5.4f;
        float f2 = 5.5f;
        //5.4四舍五入即5
        System.out.println(Math.round(f1));
        //5.5四舍五入即6
        System.out.println(Math.round(f2));
         
        //得到一个0-1之间的随机浮点数(取不到1)
        System.out.println(Math.random());
         
        //得到一个0-10之间的随机整数 (取不到10)
        System.out.println((int)( Math.random()*10));
        //开方;先对9开方,然后转成int类型
        System.out.println(Math.sqrt(9));
     //例如,(int)Math.sqrt(2)=(int)1.414=1
//次方(2的4次方) System.out.println(Math.pow(2,4)); //π System.out.println(Math.PI); //自然常数 System.out.println(Math.E);

      Math.abs();取绝对值

      Math.floor();向上取整

      Math.ceil();向下取整

    }
}

练习-质数

 找到1-1000中的质数,调优后的算法

private static ArrayList<Integer> getZhiShu1(){
        ArrayList<Integer> list=new ArrayList<>();
        list.add(2);
        for (int i=3;i<1000;i+=2){
            boolean b=true;
            for (int j=3;j<=Math.sqrt(i);j+=2){
                if(i%j==0){
                    b=false;
                }
            }
            if(b==true){
                list.add(i);
            }
        }
        return list;
    }

 

posted on 2018-06-02 23:00  lijingran  阅读(1140)  评论(0编辑  收藏  举报

导航