Home >Backend Development >PHP Problem >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!