正在查看: 标记有标签 prime number 的文章(第 1 页 / 共 1 篇)

使用PHP和Python查找100以内的所有质数

质数(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更简洁,语义化更明显。