求素数的方法 - 埃拉托色尼的筛选法(Sieve of Eratosthenes)
跳至
[1]
[全屏预览]
<html> <head> <meta charset="gb2312"> <title>求1000以内的素数</title> <style> </style> </head> <body> <?php define (N,1000); $num = "一千以内的素数 prime numbers less than ".N." : <br>"; // 根据 月生无界 提出的求素数的方法 for($i=2;$i<N;$i++){ //特殊值处理 if($i == 2){ $num .= $i.","; //System.out.println("素数:"+i); }else{//素数判断条件,从2开始除,取余,如果余值为0,表示不是素数,跳出这个数的循环判断, for($j=2;$j<$i;$j++){ if($i%$j == 0){ break; } //判断是否是素数,能除到比该值小一,且余数不为0,肯定是素数 if($i%$j != 0 && $j == $i-1){ $num .= $i.","; } } } } echo $num."<br>"; //根据 tcxu 出示的 埃拉托色尼筛选法 for($i=0;$i<N;$i++) $b[$i]=true; //将数组的元素全部赋以true for ( $i = 2; $i < N; $i++ ) // 从下标2开始递增循环 if ( $b[ $i ] ==true){// 每次找到值为true的元素 for ($j = $i + 1; $j <N; $j++ ){ /* 就用其下标作为除数,去除往后余下的元素的下标*/ if ( $j % $i == 0 ) //一旦能除尽 $b[ $j ] = false;// 将对应的元素值改为false } } for ( $i = 2; $i < N; $i++ )//从2起,打印50以内的质数 if ( $b[ $i ] ) //若元素值为true echo $i.","; // 打印出该元素的下标 ?> </body> </html>
Copy after login
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Save File Location: Where Is It & How to Protect It?
3 weeks ago
By DDD

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
