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

PHP finds prime numbers not greater than n

Release: 2023-02-27 22:32:02
Original
2478 people have browsed it

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;
        }
    }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template