Ruby Learning Notes (1) The _ruby topic of first Knowledge grammar

Source: Internet
Author: User

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

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.