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