From the technical point of view, ruby itself is really great, making the work of programmers easy and interesting!
The following code demonstrates how to find a prime number within 100:
Copy codeThe 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 calculation results.
$ 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