Home >Backend Development >PHP Problem >PHP finds prime numbers not greater than n

PHP finds prime numbers not greater than n

尚
Original
2019-10-29 14:06:492444browse

PHP finds prime numbers not greater than n

php Find a prime number not greater than n:

Use a loop to traverse and add it to the list when it is a prime number

public class Test4 {
        public static void main(String[] args) {
            Test4 t=new Test4();
            List l=t.getAll(5);
            Iterator it=l.iterator();
            while(it.hasNext()){
                System.out.println(it.next());
            }
        }
        public List<Integer> getAll(int n){
            List<Integer> prime=new ArrayList<Integer>();
            for(int i=n;i>1;i--){
                boolean flag=true;
                for(int j=i-1;j>1;j--){
                    if(i%j==0){
                        flag=false;
                        break;
                    }
                }
                if(flag){
                    prime.add(i);
                }
            }
            return prime;
        }
    }

Recommended: php server

The above is the detailed content of PHP finds prime numbers not greater than n. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP gets server error logNext article:PHP gets server error log