Friday, October 31, 2014

ruby factorial and plus each number

#!/usr/bin/env ruby

# puts '"Usage: ruby this_script_name argument(should be number) or execution permisson of Unix"'
# Plus each factorialed numbers
# Factorial. Ex) 4=1*2*3*4=24, 3=1*2*3=6
# Function(method?) of factorial beginnng


def fact(n)
    if n < 1
      raise "Argument should be more than 1"
    elsif n == 1
      return 1
    else
      return (n * fact(n-1))
    end
end
# Function(method?) of factorial ended

# Change argument to integer(to_i)
n = ARGV[0].to_i
RESULT = fact(n)
puts "Argument factorial of #{n} is #{RESULT}"

# To plus all number of factorialed. Initialize r=0. No capitalized variable
# Do not use R, or you will see "already initialized constant R warnings"
r=0
# To use array change the RESULT to "string" by to_s method.
S_RESULT = RESULT.to_s
for i in 0..(S_RESULT.length-1)
    # Revert all array members to calculate.
    r+=S_RESULT[i].to_i
end
puts "Plused result of each factorialed number is #{r}"

No comments:

Post a Comment