How to calculate double factorial (multiply odds) with recursion?[homework] - recursion

How should I alter the factorial recursion, to calculate only the odd or only the double elements of the factorial?For example if:
multiplyOdds(4)
the result should return 1*3*5*7 =105
I know how recursion works, I just need a bit of help which approach I should use.

Your function multiplyOdds(n) needs to multiply the first n odd numbers? Given that the nth odd number is equal to 2 * n - 1, you can easily write a recursive solution like the one below in Haskell:
multiplyOdds :: Int -> Int
multiplyOdds n = multiplyOddsTail n 1
multiplyOddsTail :: Int -> Int -> Int
multiplyOddsTail n acc = case n of
1 -> acc
n -> multiplyOddsTail (n - 1) (acc * (n * 2 - 1))

Related

how do I count the amount of times a (recursive) function executes itself in ocaml?

needing some help (if possible) in how to count the amount of times a recursive function executes itself.
I don't know how to make some sort of counter in OCaml.
Thanks!
Let's consider a very simple recursive function (not Schroder as I don't want to do homework for you) to calculate Fibonacci numbers.
let rec fib n =
match n with
| 0 | 1 -> 1
| _ when n > 0 -> fib (n - 2) + fib (n - 1)
| _ -> raise (Invalid_argument "Negative values not supported")
Now, if we want to know how many times it's been passed in, we can have it take a call number and return a tuple with that call number updated.
To get each updated call count and pass it along, we explicitly call fib in let bindings. Each time c shadows its previous binding, as we don't need that information.
let rec fib n c =
match n with
| 0 | 1 -> (1, c + 1)
| _ when n > 0 ->
let n', c = fib (n - 1) (c + 1) in
let n'', c = fib (n - 2) (c + 1) in
(n' + n'', c)
| _ -> raise (Invalid_argument "Negative values not supported")
And we can shadow that to not have to explicitly pass 0 on the first call.
let fib n = fib n 0
Now:
utop # fib 5;;
- : int * int = (8, 22)
The same pattern can be applied to the Schroder function you're trying to write.
You can create a reference in any higher scope like so
let counter = ref 0 in
let rec f ... =
counter := !counter + 1;
... (* Function body *)
If the higher scope happens to be the module scope (or file top-level scope) you should omit the in
You can return a tuple (x,y) where y you increment by one for each recursive call. It can be useful if your doing for example a Schroder sequence ;)

For Loop Over a Recursive Call Ocaml

I'm working on an implementation of prime decomposition in OCaml. I am not a functional programmer; Below is my code. The prime decomposition happens recursively in the prime_part function. primes is the list of primes from 0 to num. The goal here being that I could type prime_part into the OCaml interpreter and have it spit out when n = 20, k = 1.
2 + 3 + 7
5 + 7
I adapted is_prime and all_primes from an OCaml tutorial. all_primes will need to be called to generate a list of primes up to b prior to prime_part being called.
(* adapted from http://www.ocaml.org/learn/tutorials/99problems.html *)
let is_prime n =
let n = abs n in
let rec is_not_divisor d =
d * d > n || (n mod d <> 0 && is_not_divisor (d+1)) in
n <> 1 && is_not_divisor 2;;
let rec all_primes a b =
if a > b then [] else
let rest = all_primes (a + 1) b in
if is_prime a then a :: rest else rest;;
let f elem =
Printf.printf "%d + " elem
let rec prime_part n k lst primes =
let h elem =
if elem > k then
append_item lst elem;
prime_part (n-elem) elem lst primes in
if n == 0 then begin
List.iter f lst;
Printf.printf "\n";
()
end
else
if n <= k then
()
else
List.iter h primes;
();;
let main num =
prime_part num 1 [] (all_primes 2 num)
I'm largely confused with the reclusive nature with the for loop. I see that List.ittr is the OCaml way, but I lose access to my variables if I define another function for List.ittr. I need access to those variables to recursively call prime_part. What is a better way of doing this?
I can articulate in Ruby what I'm trying to accomplish with OCaml. n = any number, k = 1, lst = [], primes = a list of prime number 0 to n
def prime_part_constructive(n, k, lst, primes)
if n == 0
print(lst.join(' + '))
puts()
end
if n <= k
return
end
primes.each{ |i|
next if i <= k
prime_part_constructive(n - i, i, lst+[i], primes)
}
end
Here are a few comments on your code.
You can define nested functions in OCaml. Nested functions have access to all previously defined names. So you can use List.iter without losing access to your local variables.
I don't see any reason that your function prime_part_constructive returns an integer value. It would be more idiomatic in OCaml for it to return the value (), known as "unit". This is the value returned by functions that are called for their side effects (such as printing values).
The notation a.(i) is for accessing arrays, not lists. Lists and arrays are not the same in OCaml. If you replace your for with List.iter you won't have to worry about this.
To concatenate two lists, use the # operator. The notation lst.concat doesn't make sense in OCaml.
Update
Here's how it looks to have a nested function. This made up function takes a number n and a list of ints, then writes out the value of each element of the list multiplied by n.
let write_mults n lst =
let write1 m = Printf.printf " %d" (m * n) in
List.iter write1 lst
The write1 function is a nested function. Note that it has access to the value of n.
Update 2
Here's what I got when I wrote up the function:
let prime_part n primes =
let rec go residue k lst accum =
if residue < 0 then
accum
else if residue = 0 then
lst :: accum
else
let f a p =
if p <= k then a
else go (residue - p) p (p :: lst) a
in
List.fold_left f accum primes
in
go n 1 [] []
It works for your example:
val prime_part : int -> int list -> int list list = <fun>
# prime_part 12 [2;3;5;7;11];;
- : int list list = [[7; 5]; [7; 3; 2]]
Note that this function returns the list of partitions. This is much more useful (and functional) than writing them out (IMHO).

How to calculate 5^262144 in Erlang

Based on THIS question, I realized that calculating such numbers seems not possible in regular ways.
Any suggestions?
It is possible, but you need an algorithm that is a bit more clever than the naive solution. If you write the naive power function, you do something along the lines of:
pow(_, 0) -> 1;
pow(A, 1) -> A;
pow(A, N) -> A * pow(A, N-1).
which just unrolls the power function. But the problem is that in your case, that will be 262144 multiplications, on increasingly larger numbers. The trick is a pretty simple insight: if you divide N by 2, and square A, you almost have the right answer, except if N is odd. So if we add a fixing term for the odd case, we obtain:
-module(z).
-compile(export_all).
pow(_, 0) -> 1;
pow(A, 1) -> A;
pow(A, N) ->
B = pow(A, N div 2),
B * B * (case N rem 2 of 0 -> 1; 1 -> A end).
This completes almost instantly on my machine:
2> element(1, timer:tc(fun() -> z:pow(5, 262144) end)).
85568
of course, if doing many operations, 85ms is hardly acceptable. But computing this is actually rather fast.
(if you want more information, take a look at: https://en.wikipedia.org/wiki/Exponentiation_by_squaring )
If you are interested how compute power using same algorithm as in I GIVE CRAP ANSWERS's solution but in tail recursive code, there it is:
power(X, 0) when is_integer(X) -> 1;
power(X, Y) when is_integer(X), is_integer(Y), Y > 0 ->
Bits = bits(Y, []),
power(X, Bits, X).
power(_, [], Acc) -> Acc;
power(X, [0|Bits], Acc) -> power(X, Bits, Acc*Acc);
power(X, [1|Bits], Acc) -> power(X, Bits, Acc*Acc*X).
bits(1, Acc) -> Acc;
bits(Y, Acc) ->
bits(Y div 2, [Y rem 2 | Acc]).
It simple since Erlang uses arbitrary-precision for integers(big numbers) you can define own function pow for integer, for example:
-module(test).
-export([int_pow/2]).
int_pow(N,M)->int_pow(N,M,1).
int_pow(_,0,R) -> R;
int_pow(N,M,R) -> int_pow(N,M-1,R*N).
Note, I did not check the arguments and showed the implementation for your example.
You can do:
defmodule Pow do
def powa(x, n), do: powa(x, n, 1)
def powa(_, 0, acc), do: acc
def powa(x, n, acc), do: powa(x, n-1, acc * x)
end
Apparently
Pow.powa(5, 262144) |> to_string |> String.length
yields
183231
long number that you were curious about.

SML: Keeping track of number of iterations

I'm sure there's a way to do this elegantly in SML but I'm having difficulty keeping track of the number of iterations (basically the number of times my function has been called).
I'm trying to write a function that evaluates to a pair of numbers, one for the floor of the answer and the other for the remainder. So if you called:
divmod(11, 2), you'd get (5, 1) back.
Here's what I have so far:
divmod(number : int, divisor : int) =
if number < divisor then
(number, count)
else
divmod(number - divisor, divisor);
Obviously, I haven't set up my count variable so it won't compile but that's the idea of the algorithm. All that's left is initializing count to 0 and being able to pass it between recursive calls. But I'm only allowed the two parameters for this function.
I can, however, write auxiliary functions.
Thoughts?
If SML has support for nested functions you could do like this:
divmod(number : int, divisor : int) =
_divmod(n : int, d : int, count : int) =
if n < d then
(count, n)
else
_divmod(n - d, d, count + 1)
_divmod(number, divisor, 0)
Personally, I like the fact that SML isn't a pure functional language. Keeping track of function calls is naturally done via side effects (rather than explicitly passing a counter variable).
For example, given a generic recursive Fibonacci:
fun fib 0 = 0
| fib 1 = 0
| fib n = fib(n-2) + fib(n-1);
You can modify it so that every time it is called it increments a counter as a side effect:
counter = ref 0;
fun fib 0 = (counter := !counter + 1; 0)
| fib 1 = (counter := !counter + 1; 1)
| fib n = (counter := !counter + 1; fib(n-2) + fib(n-1));
You can use this directly or wrap it up a bit:
fun fibonacci n = (
counter :=0;
let val v = fib n
in
(!counter,v)
end);
With a typical run:
- fibonacci 30;
val it = (2692537,832040) : int * int
(Which, by the way, shows why this version of the Fibonacci recursion isn't very good!)

Reversing an int in OCaml

I'm teaching myself OCaml, and the main resources I'm using for practice are some problem sets Cornell has made available from their 3110 class. One of the problems is to write a function to reverse an int (i.e: 1234 -> 4321, -1234 -> -4321, 2 -> 2, -10 -> -1 etc).
I have a working solution, but I'm concerned that it isn't exactly idiomatic OCaml:
let rev_int (i : int) : int =
let rec power cnt value =
if value / 10 = 0 then cnt
else power (10 * cnt) (value/10) in
let rec aux pow temp value =
if value <> 0 then aux (pow/10) (temp + (value mod 10 * pow)) (value / 10)
else temp in
aux (power 1 i) 0 i
It works properly in all cases as far as I can tell, but it just seems seriously "un-OCaml" to me, particularly because I'm running through the length of the int twice with two inner-functions. So I'm just wondering whether there's a more "OCaml" way to do this.
I would say, that the following is idiomatic enough.
(* [rev x] returns such value [y] that its decimal representation
is a reverse of decimal representation of [x], e.g.,
[rev 12345 = 54321] *)
let rev n =
let rec loop acc n =
if n = 0 then acc
else loop (acc * 10 + n mod 10) (n / 10) in
loop 0 n
But as Jeffrey said in a comment, your solution is quite idiomatic, although not the nicest one.
Btw, my own style, would be to write like this:
let rev n =
let rec loop acc = function
| 0 -> acc
| n -> loop (acc * 10 + n mod 10) (n / 10) in
loop 0 n
As I prefer pattern matching to if/then/else. But this is a matter of mine personal taste.
I can propose you some way of doing it:
let decompose_int i =
let r = i / 10 in
i - (r * 10) , r
This function allows me to decompose the integer as if I had a list.
For instance 1234 is decomposed into 4 and 123.
Then we reverse it.
let rec rev_int i = match decompose_int i with
| x , 0 -> 10 , x
| h , t ->
let (m,r) = rev_int t in
(10 * m, h * m + r)
The idea here is to return 10, 100, 1000... and so on to know where to place the last digit.
What I wanted to do here is to treat them as I would treat lists, decompose_int being a List.hd and List.tl equivalent.

Resources