java基础总结(二)

来源:互联网 发布:创业软件 俞青 编辑:程序博客网 时间:2024/06/05 08:26

文章是参考:http://blog.csdn.net/lifetragedy/article/details/9812419 的总结

总结源码地址:https://github.com/TangXW777/java-base/tree/master

计算20内的全部质数:
public class PrimeTest {    public static boolean isPrime(int num){        for(int i = 2; i < (num - 1); i++){            if(num % i == 0){                return false;            }        }        return true;    }    public static void main(String[] args) {        for(int j = 2; j <= 20; j++){            if(isPrime(j)){                System.out.println("is Prime:" + j);            }        }    }}
这是最常见的做法,就是每个数去看是不是只有1和它本身可以整除,但这种做法效率较低。还有一种做法是把左右的偶数去掉留下质数。

public class PrimeTest2 {    public static void main(String[] args) {        int n = 20;        int[] array = new int[n];        for (int i = 2; i < n; i++) {            array[i] = i;        }        for (int i = 2; i < n; i++) {            if (array[i] != 0) {                int j, temp;                temp = array[i];                for (j = 2 * temp; j < n; j = j + temp) {                    array[j] = 0;                }                System.out.println("\n");            }        }    }}

约瑟夫环算法:
愿意就是有一批人,连城一个环,依次报数,报到3的人出局,最后剩下一个人也踢出局,问依次出局的人是原来圈内的几号?
循环算法:
        int n = 20;        int flag = 0;        while(true){            flag=(flag + 1) % n;            System.out.println(flag);        }
具体实现:
public class JosephCircle {    public void josephCircle(int n, int k){        int flag = 0;        boolean[] kick = new boolean[n];  // 初始值都为false        int counter = 0;        int accumulate = 0;        while (true){            if(!kick[flag]){  // 如果这个人还在环中,没被踢出                accumulate++;                if(counter == n - 1){ // 如果是最后一个人                    System.out.println("the last kick person ===" + (flag + 1));                    break;                }                if(accumulate == k){  // 如果是3,则踢出                    kick[flag] = true;                    System.out.println("the kick person ===" + (flag + 1));                    accumulate = 0; // 重置                    counter++;  // 踢出人数+1                }            }            flag = (flag + 1) % n;        }    }    public static void main(String[] args) {        JosephCircle j = new JosephCircle();        j.josephCircle(20, 3);    }}





原创粉丝点击