Skip to content

Instantly share code, notes, and snippets.

@Wonicon
Last active August 29, 2015 14:16
Show Gist options
  • Save Wonicon/57dec09a8b73fa30b490 to your computer and use it in GitHub Desktop.
Save Wonicon/57dec09a8b73fa30b490 to your computer and use it in GitHub Desktop.
Misc of Ruby
#!/usr/bin/env ruby
print "input n: "
n = gets.chomp.to_i
r = 0
(1..(n - 1)).each do |i|
((i + 1)..(n)).each do |j|
(1..j).each {r += 1}
end
end
puts "The algo4: #{r}"
m = n * (n + 1) * (n - 1) / 3
puts "The formula: #{m}"
r = 0
(1..n).each do |i|
(1..i).each do |j|
(j..(i+j)).each {r += 1}
end
end
puts "The algo5: #{r}"
m = n * (n + 1) * (n + 2) / 3
puts "The formula: #{m}"
r = 0
(1..n).each do |i|
(1..i).each do |j|
(j..i+j).each do |k|
(1..i+j-k).each { r += 1 }
end
end
end
puts "The algo6: #{r}"
m = n * (n + 1) * (3 * n + 1) * (n + 2) / 24
puts "The formula: #{m}"
r = 0
k = 0
(1..n).each do |i|
(i+1..n).each do |j|
((i+j-1)..n).each {r += 1}
end
end
puts "The algo7: #{r}"
if n % 2 == 0
m = n * (n + 2) * (2 * n - 1) / 24
else
m = (n - 1) * (n + 1) * (2 * n + 3) / 24
end
puts "The formula: #{m}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment