自学java关于Hashmap输出素数

package javaclass;


import java.util.Map;
import java.util.HashMap;
import static java.lang.Math.random; //随机数

public class A3 {
    public static void main(String[] args) {
        int[] number = new int[101];
        int[] a = new int[100000000];
        int flag = 0;
        int temp =0;
        //double m=random();
        System.out.print("原始数为:");
        for (int i = 2; i < 101; i++) {
            number[i] = i;
            System.out.print(number[i] + ",");
            /*System.out.print("");
            System.out.println(m);*/
        }
        System.out.println("");
        System.out.print("新数组为:");
        for (int i = 2; i <= 100; i++) {
            for (int m = 2; m <= i; m++) {
                if (i % m != 0) {
                    a[flag] = number[i];
                    System.out.print(a[flag] + ",");
                    flag++;
                }
            }
        }
        System.out.println("");
        HashMap<Integer,Integer> msy=new HashMap<Integer,Integer>();
       for(flag=0;flag<a.length;flag++){
           if(!msy.containsKey(a[flag])){msy.put(a[flag],1);}
           else{
               msy.put(a[flag],(msy.get(a[flag]))+1);
           }
       }
        //System.out.println(msy.size());  哈希树长度范围
       System.out.print("素数为:"+"2,");
       for(Map.Entry<Integer,Integer> MSY:msy.entrySet())     //由于Hashmap,数组有长度而键值对没有直接长度计算,为了将最后一个数找出的独创方式
       {
           if ((MSY.getValue() == (MSY.getKey() - 2))) {
               // System.out.print(MSY.getKey()+",");
               temp = MSY.getKey();
           }
       }
       for(Map.Entry<Integer,Integer> MSY:msy.entrySet()) //键值对匹配
           if((MSY.getValue()==(MSY.getKey()-2))&&MSY.getKey()!=temp){
               System.out.print(MSY.getKey()+",");
           }
           else if(MSY.getKey()==temp){System.out.print(temp+"。");}
           }
       }



猜你喜欢

转载自blog.csdn.net/qq_37455615/article/details/80199458