Ruby, PHP, Shell to achieve 50 of the Prime _ruby topic

Source: Internet
Author: User
Tags php code

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.