Dec 13 2007

用ruby完成c程序设计书的习题

Posted by admin

Tags:

最大公约数和最小公倍数
m
n求余为a, a不等于0
m <- n, n <- a, 继续求余
否则
n 为最大公约数
最小公倍数 = 两个数的积 / 最大公约数

a=gets.to_i
b=gets.to_i
max=a*b
if a
b,a=a,b
end
re=a%b #remainder
while re!=0
a,b=b,re
re=a%b
end
print “Greatest common divisor: “,b,”\n”,”lease common multiple: “,max/b

水仙花数

for number in 100..999
hundred=number/100
ten=(number-hundred*100)/10
a=(number-hundred*100)%10
total=hundred**3+ten**3+a**3
if number==total
print "#{number} is right\n"
end
end

一个球从100m高度自由落下,每次落地后反跳回原高度的一半,再反弹。求它在第10次落地时,共经过多少米?第10次反弹多高?

x=100.0
y=0.0
10.times do
y+=x/2+x
x=x/2
end
puts y,x

猴子吃桃

=begin
# recursion
def monkey(n)
if n==1
c=1
else
c=(monkey(n-1)+1)*2
end
c
end
puts monkey(10)
=end
x=1
10.times do
puts x
x=(x+1)*2
end

求素数
for m in 1..300000
k=Math.sqrt(m)
is=true
for i in 2..k
if m%i==0
is=false
break
end
end
if is
print m," "
end
end

Filed under : technology |

Leave a Reply