当前位置:Gxlcms > PHP教程 > php求不大于n的质数

php求不大于n的质数

时间:2021-07-01 10:21:17 帮助过:38人阅读

php求不大于n的质数:

使用循环遍历、当为质数时加入list中

  1. public class Test4 {
  2. public static void main(String[] args) {
  3. Test4 t=new Test4();
  4. List l=t.getAll(5);
  5. Iterator it=l.iterator();
  6. while(it.hasNext()){
  7. System.out.println(it.next());
  8. }
  9. }
  10. public List<Integer> getAll(int n){
  11. List<Integer> prime=new ArrayList<Integer>();
  12. for(int i=n;i>1;i--){
  13. boolean flag=true;
  14. for(int j=i-1;j>1;j--){
  15. if(i%j==0){
  16. flag=false;
  17. break;
  18. }
  19. }
  20. if(flag){
  21. prime.add(i);
  22. }
  23. }
  24. return prime;
  25. }
  26. }

推荐:php服务器

以上就是php求不大于n的质数的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行