使用PHP和Python查找100以内的所有质数
发布于: May 10, 2010, 4:41 am 分类: PHP/MySQL 作者: Saturn
质数(Prime Numbers)就是只能被1和它本身整出的自然数。本文描述查找100以内质数的算法分别在PHP和Python中的实现,仅作记录。
PHP版查找100以内的所有质数:
<?php
//script by Saturn @ cnsaturn.com
for($i=2; $i< 100; $i++)
{
//$count is used to check whether or not the internal loop is exhausted
$count = 0;
for($j = 2; $j < $i; $j++)
{
if($i % $j == 0)
{
$count ++;
echo "$i = $j * " . $i/$j .".\n";
break;
}
}
if($count == 0)
{
echo "$i is a prime number. \n";
}
}
Python版(via)查找100以内的所有质数:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'
可以看到虽然两种语言对质数查找的实现都比较简单,但相比PHP而言,Python更简洁,语义化更明显。
回应此文
你也可以选择引用此文章.