From the technical point of view, Ruby itself is really nice.ProgramThe work of Members becomes easy and interesting!
The followingCodeDemonstrate how to find a prime number less than 100:
Copy code The Code is as follows: using system;
Namespace Mersenne
{
Class Program
{
Static void main (string [] ARGs)
{
For (INT I = 2; I <50; I ++)
{
If (checkdigital (I ))
{
Console. writeline ("{0}", I );
}
}
Console. Readline ();
}
Static bool checkdigital (int I)
{
If (I <= 1) {return false ;}
If (I = 2) {return true ;}
Bool _ result = true;
For (Int J = 2; j <I; j ++)
{
If (I % J = 0)
{
_ Result = false;
Break;
}
}
Return _ result;
}
}
}
Refer to this idea and translate it into Ruby:Copy codeThe Code is as follows: for I in 2 .. 100
Flag = true;
For J in 2... I
If I % J = 0
Flag = false;
Break;
End
End
If flag
Print I, "\ n"
End
End
The flexibility of Ruby syntax can be reduced to the following code:Copy codeThe Code is as follows: for I in 2 .. 100
Flag = true;
(2 .. I). Each {| n | flag = false if I % N = 0}
Print I, "\ n" if flag
End
You can also write it as follows:Copy codeThe Code is as follows: def checknum? (Num)
Return true if num = 2
F = true;
For J in 2... num
If num % J = 0
F = false;
Break
End
End
Return F
End
(2 .. 50). Each {| x | print X, "\ n" If checknum? (X )}
Another implementation:Copy codeThe Code is as follows: $ arr = [] # defines a global array to save the calculation result.
$ Arr [0] = 2
# Definition method: add the odd prime numbers within n to $ Arr (the odd prime numbers must be at the same time, except for 2)
Def add_prime (N)
3. Step (n, 2) {| num | $ arr <num if is_prime? Num}
End
# Define the method to determine whether it is a prime number
Def is_prime? (Number)
J = 0
While $ arr [J] * $ arr [J] <= Number
Return false if Number % $ arr [J] = 0
J + = 1
End
Return true
End
Add_prime (50); # Call
Puts $ arr. Join (',') # output result
Author: Yang Guo under the bodhi tree