In terms of technology alone, Ruby is really cool, making the programmer's job a fun and easy task!
The following code shows how to find the prime number within 100:
Copy Code code as follows:
Using System;
Namespace Mersenne
{
Class Program
{
static void Main (string[] args)
{
for (int i = 2; i < 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 a ruby version:
Copy Code code 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
With the flexibility of Ruby syntax, you can streamline the following code:
Copy Code code 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
It can be written like this.
Copy Code code 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 Code code as follows:
$arr =[] #定义一个全局数组 to save the results of the calculation
$arr [0] = 2
#定义方法, the odd prime number within N is added to the $arr (prime number is also positive for odd numbers, excluding 2)
def add_prime (N)
3.step (n,2) {|num| $arr <<num if is_prime? num}
End
#定义方法 determine whether 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); #调用
Puts $arr. Join (', ') #输出结果
The young under the Banyan tree