Ruby, PHP, and Shell are used to calculate prime numbers of less than 50. rubyshell

Source: Internet
Author: User

Ruby, PHP, and Shell are used to calculate prime numbers of less than 50. rubyshell

Ruby's method of finding the prime number within 50 is the easiest way to compare PHP and SHELL methods, but the SHELL can use the factor command, while PHP does not have the corresponding function for finding the prime number, you need to design your own algorithms. There should be better and simpler methods for comparison and learning.
Copy codeThe Code is as follows:
# Encoding: UTF-8
# Calculate the prime number within 50 (note the difference between the number and the number)
 
For I in 2 .. 50 #1 is not a prime number by default, so it is excluded from the range of 1-50
F = true # starting from the assumption that each number is a prime number
For p in 2... I # a positive integer smaller than itself (except 1 and itself)
If I % p = 0 # if division is possible
F = nil # The number is not a prime number.
Break # And jump out of this loop
End # if end
End # end of the Inner Loop
Print I, "" if f # if this number is set to the starting assumption, print
End # outer loop ends

The PHP code is as follows:
Copy codeThe Code is as follows:
<? Php
Echo "The following program outputs a prime number of less than 50 :";
For ($ m = 1; $ m <= 50; $ m ++) {// the first layer of the loop, which loops 1-50 directly to all numbers
$ K = 0; // counter Initialization
For ($ I = 1; $ I <= $ m; $ I ++) {// Layer 2 loop, loop 1-$ m directly to all numbers, $ m <= $ n
If ($ m % $ I = 0) {// modulo operation, if the remainder is 0, K auto-increment 1
$ K ++;
}
}
If ($ k = 2) {// if k is equal to 1 or 2, it is a prime number and is output
Echo $ m ."";
}
}
?>

The SHELL method is a little simpler. The Code is as follows:

Copy codeThe Code is as follows:
#! /Bin/bash
# Factor is a shell command, which can be used to find all prime numbers in the followed number.
For I in {2... 50}
Do
Factor $ I | awk-F' [:] ''{if (NF = 3) print $1 }'
Done

Related Article

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.