Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define the function squarefact::Int -> Int that computes for any positive integer n the squared factorial (n!)^2 == (1 * ...* n)^2

Tags:

haskell

I am trying to define a function that computes for any positive integer the square of its factorial

(I am a beginner in Haskell any tips or help is appreciated)

I have tried a couple different ways one i believe to work and one definition i don't understand why it doesn't work

Function i believe works:

 squarefact:: Int -> Int
 squarefact 0 = 1
 squarefact n = n * n * squarefact(n-1)

Function I don't understand why it doesn't work:

squarefact:: Int -> Int
squarefact 0 = 1
squarefact n = (n * squarefact(n-1) ) * (n * squarefact(n-1) )

An explanation and walk through of the dunctions defined would help me understand them better thanks.

like image 233
program.exe Avatar asked Jan 21 '21 21:01

program.exe


2 Answers

The equation

squarefact n = (n * squarefact(n-1) ) * (n * squarefact(n-1) )

could be rewritten in mathematical notation as

(n!)^2 = n * ((n-1)!)^2 * n * ((n-1)!)^2

but this identity is incorrect. The right hand side includes factors 1,2,....,n-1 four times instead of only two, as in the left hand side.

By comparison,

squarefact n = n * n * squarefact(n-1)

is correct, since on both sides all the factors occur exactly twice.

like image 189
chi Avatar answered Oct 26 '22 19:10

chi


A factorial function can be defined in Haskell as

factorial n = product [1..n]

(where product is a function that calculates the product of all the numbers in a given list.)

Hence,

squarefact n = square (factorial n) =
  = square (product [1..n])
  = product [1..n] * product [1..n]
  = 1 * 2 * 3 * ... * (n-1) * n *
    1 * 2 * 3 * ... * (n-1) * n
  = product [1..(n-1)] * n * product [1..(n-1)] * n
  = n * n * square (product [1..(n-1)])
  = n * n * squarefact (n-1)

The equality re-writes break down for n=0 ( squarefact 0 /= 0 * 0 * squarefact (-1) ), so it must be handled as a special case.

like image 2
Will Ness Avatar answered Oct 26 '22 19:10

Will Ness