Ruby's method of finding primes within 50, feel the comparison of PHP and Shell method is the simplest, but the shell can use the factor command, and PHP does not have the corresponding function of the prime number, you need to design the algorithm, three ways to compare the study, there should be more excellent and simpler way.
Copy Code code as follows:
#encoding: Utf-8
#求50以内的素数 (Note the number ... And... The difference)
For I in 2..50 #1默认不为素数, so excluded from the 1-50 range
F=true #起始假定每个数都是素数
For P in 2...i #比自身小的正整数 (except for 1 and itself)
If I%p==0 #如果能整除
F=nil# then this number is not prime
Break #并且跳出这层循环
End # if ending
End #内层循环结束
Print I, "" If f #如果这个数保持起始假定, printing
End #外层循环结束
The PHP code is as follows:
Copy Code code as follows:
<?php
echo "The following program will output a prime number within 50:";
For ($m =1 $m <=50; $m + +) {//First level loop, loop 1-50 Direct all numbers
$k = 0; Counter initialization
For ($i =1 $i <= $m; $i + +) {//second tier loop, loop 1-$m all numbers directly, $m <= $n
if ($m% $i ==0) {//modulo operation, if the remainder is 0,k from 1
$k + +;
}
}
if ($k ==2) {//If the value of K equals 1 or 2, then the prime number is output
echo $m. " ";
}
}
?>
The Shell's approach is slightly simpler, and the code is as follows:
Copy Code code as follows:
#!/bin/bash
#factor是shell命令, you can find all the primes in the following numbers.
For i in {2..50}
Todo
Factor $i | Awk-f ' [:] ' {if (NF = 3) print $} '
Done