Last active
August 29, 2015 14:16
-
-
Save Wonicon/57dec09a8b73fa30b490 to your computer and use it in GitHub Desktop.
Misc of Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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