繁体   English   中英

查找素数的 ArrayList 直到给定的数字

[英]Find the ArrayList of prime numbers till the given number

所以我需要编写一个程序,它接受一个数字并打印整数数组列表,直到输入的数字(包括)。 例如,如果我们写 7,程序需要打印:1,2,3,5,7。 我尝试了一些我在互联网上看到的方法,但没有成功。

    package com.company;
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.Scanner;

    public class Main {


        public static void main(String[] args) {


            Scanner scanner = new Scanner(System.in);
            int input = scanner.nextInt();
            ArrayList<Integer> AYE = new ArrayList<Integer>();
            int flag = 0;
            for(int i = 1; i<=input; i++){
                if(i==1 || i==2 || i==3){
                    AYE.add(i);
                }else{
                    for(int a = 2; a<=(int)Math.sqrt(input+1); a++){
                        if(input%a==0){
                            flag = 1;
                            break;
                        }else{
                            flag=0;
                        }
                    }
                    if(flag==0){
                        AYE.add(i);
                    }
                }

            }




            Qaytarmaq(AYE)
            ;


         }
        public static void Qaytarmaq(ArrayList<Integer> AYE){
            for (int j = 0; j < AYE.size(); j++) {
                System.out.println(AYE.get(j));


            }
        }
   }

尝试这个。

public static List<Integer> primes(int max) {
    return IntStream.rangeClosed(2, (int)Math.sqrt(max))
        .mapToObj(i -> (IntPredicate) k -> k == i || k % i != 0)
        .reduce(IntStream.rangeClosed(2, max),
            (s, p) -> s.filter(p), (a, b) -> IntStream.concat(a, b))
        .boxed()
        .toList();
}

public static void main(String[] args) throws ClassNotFoundException {
    System.out.println(primes(100));
}

输出:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

久经考验

import java.util.*;
public class HelloWorld {
    public static void main(String[] args) {
        int n=7; // you can change value of n
        ArrayList<Integer> list=new ArrayList<>();
        list.add(2);
       for(int i=3;i<=n;i++)
       {
           boolean flag=false;
           for(int j=2;j<=Math.sqrt(i);j++)
           {
               if(i%j==0)
               {
                  
                   flag=true;
                   break; 
               }
           } 
    
           if(!flag) list.add(i);
           
       }
       System.out.println(list);
    }
}

输出:

[2, 3, 5, 7]

注: 1既不是prime也不是composite

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM