Hackety Hacking Problem Factorial: Difference between revisions

From OLPC
Jump to navigation Jump to search
No edit summary
Line 40: Line 40:
puts("Enter the no. whose factorial to be calculated: ")
puts("Enter the no. whose factorial to be calculated: ")


n=gets.chomp.to_i #Convert the incoming string input into an integer.To do calculations.
n=gets.chomp.to_i #Convert the incoming string input into an integer.To do calculations.


#Method fact which is used to calculate factorial
#Method fact which is used to calculate factorial


def fact(n,k)
def fact(n,k)
k=k*n
k=k*n
k
k
end
end


count=1
count=1
while count<n
while count<n
f=fact(count+1,f)
f=fact(count+1,f)
count = count + 1
end
end



Revision as of 17:45, 24 October 2007

Problem Statement

You have a word each made up of different letter no letter repeated.You have been given the length of the word.Now the problem is that you have to print the number of ways in which the letters can be arranged to return a new word. For Example: Word Length=3 take a word "bat" It can be written in 6 different ways: abt atb bat bta tab tba

So you have to write a program which takes the word length as the input from the user,And prints the number of ways in which they can be arranged.

Constrains

  • There can be more than one way to solve it.
  • You have to use recursion.
  • You have to give as many no.of solution as you can give

Help

Have you ever heard the word recursion, if not than let me explain. It is the name for algorithm which is to call the function from within itself but with changed parameters.

Sample Output

Enter the word length : 5
The number of ways the word can be arranged is = 120

Curriculum Connections

  • How to find factorial with the help of ruby.
  • What is recursion & its importance.
  • How to convert a recursion version of a program into iterative version.

Solution

I st Solution

f=1
puts("Enter the no. whose factorial to be calculated: ")

n=gets.chomp.to_i #Convert the incoming string input into an integer.To do calculations.

#Method fact which is used to calculate factorial

def fact(n,k)
k=k*n
k
end

count=1
while count<n
f=fact(count+1,f)
count = count + 1
end

puts f

IInd Solution This one is the iterative version of this program

f=1
 
puts("Enter the no. whose factorial to be calculated: ")

n=gets.chomp.to_i                                        #Convert the incoming string input into an integer.To do calculations.

n.times do|x|
        f=f*x
end
puts f