Finding power functions minus 1 on OCaml - function

I wrote a function that finds power. But I want to program to find minus 1 of power function. How can I do that ? For example power 3 4 = 80, power 2 3 = 7
Here is the code
let rec power m n =
if n = 0 then 1
else m * power m (n-1) ;;

Well, you'll have to subtract 1 after calculating the power then:
let powerMinus1 m n = (power m n) - 1;;
Or if you need it self-contained you can use an inner function:
let powerMinus1 m n =
let rec power n =
...
in (power n) - 1;;

Related

Recursive Function that divides two integers and returns result and remainder

I am trying to create a recursive function that divides two integers n and m and then displays the result and the remainder of the division.
Basicly I created two separate functions which do exactly what I want:
let rec div1 (n: int, m: int): int =
if n<m then n else div1(n-m, m)
printfn "Remainder: %i" (div1(5,5))
let rec div2 (n: int, m: int): int =
if n<m then 0 else 1+div2(n-m, m)
printfn "Result: %i" (div2(5,5))
The thing is, I want to do them both at once, I mean in one function like let rec div12 (n: int) (m : int): int * int = , not in two separate.
I am not sure how exactly this would work on F#.
A function may return more than just a number. For example, a function may return a tuple of two numbers:
let f x = (x, x+5)
f 5
> (5, 10)
Further, you can destructure return value of such a function in a similar way:
let (x, y) = f 5
x
> 5
y
> 10
Now we can use this to have our div+mod function return two results - remainder and quotient:
let rec divMod n m =
if n < m
then
(n, 0)
else
let (remainder, quotient) = divMod (n-m) m
(remainder, quotient + 1)
Note how this function simply combines results of your div1 and div2 in a tuple, then destructures them after the recursive call.
divMod 5 5
> (0, 1)
divMod 5 3
> (2, 1)
divMod 7 3
> (1, 2)
Also note that I'm using curried parameters divMod n m instead of tupled parameters as you do div1 (n, m). Ultimately this is a matter of taste, but as a pro tip, I'd like to point out that curried parameters turn out to be much more useful in practice.

Find (num * (pow(b, p) - 1) / den) % mod where p is very large(10 ^ 18)

I want to find (num * (pow(b, p) - 1) / den) % mod. I know about binary exponentiation. But we can't do it straightforward. It is guaranteed that the numerator is divisible by the denominator. That means
[num * (pow(b, p) - 1)] % den == 0
constraints on mod: are 1 <= mod <= 10 ^ 9 and mod might be prime or composite
constraints on b: 1 <= b <= 10
constraints on p: 1 <= p <= (10^18)
constraints on num: 1 <= num <= (10^9)
constraints on den: 1 <= den <= (10^9)
Here pow(b, p) means b raised to power p(b ^ p). It is guaranteed that the numerator is divisible by the denominator. How can I do it with binary exponentiation
Your expression should rewritten to simplIfy it. First let k=num/den, with k integer according to your question.
So you have to compute
(k×(b^p-1))mod m=( (k mod m) × ((b^p -1) mod m) ) mod m
= ( (k mod m) × ( (b^p mod m) -1 mod m ) mod m ) mod m
= ((k mod m) × ((b^p mod m) + m-1) mod m) mod m (1)
So the real problem is to compute b^p mod m
Many languages (python, java, etc) already have a modular exponentiation in their standard libraries. Consult the documentation and use it. Otherwise, here is a C implementation.
unsigned long long modexp(unsigned long long b, unsigned long long e, unsigned long long m) {
if (m==1) return 0;
unsigned long long res=1;
unsigned long long bb = b % m;
while (e) {
if (e & 1)
res = (res*b) % m;
e >>= 1;
bb = (bb*bb) % m;
}
return res;
}
The implementation uses long long to fit your constraints. It relies on the classical trick of binary exponentiation. All values of b^l, where l is a power of two (l=2^t) are computed and stored in var bb and if the corresponding tth bit of e is set, this value of b^l is integrated in the result. Bit testing is done by checking the successive parities of e, while shifting e rightward at each step.
Last, the fact that (a×b)mod m=((a mod m)×(b mod m))mod m is used to avoid computation on very large numbers. We always have res<m and bb<m and hence res and bb are codable on standard integers.
Then you just have to apply (1) to get the final result.
EDIT according to the precisions given in the comments
To compute n=(3^p-1)/2 mod m, one can remark that
(3^p-1)/2 = x*m + n (as 3^p-1 is even, x is an integer, 0&leq;n<m)
3^p-1=x*2*m+2n (0&leq;2n<2m)
so 2n=(3^p-1) mod 2m
We can just apply the previous method with a modulo of 2*m, and divide the result (that will be even) by 2.

Putting last element of list in the first index "n" times SML

I'm trying to put the last element of a list in the front of the list while keeping the rest of the elements in the same order N times. I can do it once with this function, but I want to add another parameter to the function so that the function in called N times.
Code:
fun multcshift(L, n) =
if null L then nil
else multcshift(hd(rev L)::(rev(tl(rev L))));
Thanks
To make the parameter n work, you need recursion. You need a base case at which point the function should no longer call itself, and a recursive case where it does. For this function, a good base case would be n = 0, meaning "shift the last letter in front 0 times", i.e., return L without modification.
fun multcshift(L, n) =
if n = 0
then L
else multcshift( hd(rev L)::rev(tl(rev L)) , n - 1 )
The running time of this function is terrible: For every n, reverse the list three times!
You could save at least one of those list reversals by not calling rev L twice. E.g.
fun multcshift (L, 0) = L
| multcshift (L, n) =
let val revL = rev L
in multcshift ( hd revL :: rev (tl revL) , n - 1 ) end
Those hd revL and rev (tl revL) seem like useful library functions. The process of applying a function to its own output n times seems like a good library function, too.
(* Return all the elements of a non-empty list except the last one. *)
fun init [] = raise Empty
| init ([_]) = []
| init (x::xs) = x::init xs
(* Return the last element of a non-empty list. *)
val last = List.last
(* Shift the last element of a non-empty list to the front of the list *)
fun cshift L = last L :: init L
(* Compose f with itself n times *)
fun iterate f 0 = (fn x => x)
| iterate f 1 = f
| iterate f n = f o iterate f (n-1)
fun multcshift (L, n) = iterate cshift n L
But the running time is just as terrible: For every n, call last and init once each. They're both O(|L|) just as rev.
You could overcome that complexity by carrying out multiple shifts at once. If you know you'll shift one element n times, you might as well shift n elements. Shifting n elements is equivalent to removing |L| - n elements from the front of the list and appending them at the back.
But what if you're asked to shift n elements where n > |L|? Then len - n is negative and both List.drop and List.take will fail. You could fix that by concluding that any full shift of |L| elements has no effect on the result and suffice with n (mod |L|). And what if n < 0?
fun multcshift ([], _) = raise Empty
| multcshift (L, 0) = L
| multcshift (L, n) =
let val len = List.length L
in List.drop (L, len - n mod len) #
List.take (L, len - n mod len) end
There are quite a few corner cases worth testing:
val test_zero = (multcshift ([1,2,3], 0) = [1,2,3])
val test_empty = (multcshift ([], 5); false) handle Empty => true | _ => false
val test_zero_empty = (multcshift ([], 0); false) handle Empty => true | _ => false
val test_negative = (multcshift ([1,2,3,4], ~1) = [2,3,4,1])
val test_nonempty = (multcshift ([1,2,3,4], 3) = [2,3,4,1])
val test_identity = (multcshift ([1,2,3,4], 4) = [1,2,3,4])
val test_large_n = (multcshift [1,2,3,4], 5) = [4,1,2,3])
val test_larger_n = (multcshift [1,2,3,4], 10) = [3,4,1,2])

Using nested functions to find product of numbers

I need to make a function that given natural number n, calculates the product
of the numbers below n that are not divisible by
2 or by 3 im confused on how to use nested functions in order to solve this problem (also new to sml ) here is my code so far
fun countdown(x : int) =
if x=0
then []
else x :: countdown(x-1)
fun check(countdown : int list) =
if null countdown
then 0
else
It is not clear from the question itself (part of an exercise in some class?) how we are supposed to use nested functions since there are ways to write the function without nesting, for example like
fun p1 n =
if n = 1 then 1 else
let val m = n - 1
in (if m mod 2 = 0 orelse m mod 3 = 0 then 1 else m) * p1 m
end
and there are also many ways to write it with nested functions, like
fun p2 n =
if n = 1 then 1 else
let val m = n - 1
fun check m = (m mod 2 = 0 orelse m mod 3 = 0)
in (if check m then 1 else m) * p2 m
end
or
fun p3 n =
let fun check m = (m mod 2 = 0 orelse m mod 3 = 0)
fun loop m =
if m = n then 1 else
(if check m then 1 else m) * loop (m + 1)
in loop 1
end
or like the previous answer by #coder, just to give a few examples. Of these, p3 is somewhat special in that the inner function loop has a "free variable" n, which refers to a parameter of the outer p3.
Using the standard library, a function that produces the numbers [1; n-1],
fun below n = List.tabulate (n-1, fn i => i+1);
a function that removes numbers divisible by 2 or 3,
val filter23 = List.filter (fn i => i mod 2 <> 0 andalso i mod 3 <> 0)
a function that calculates the product of its input,
val product = List.foldl op* 1
and sticking them all together,
val f = product o filter23 o below
This generates a list, filters it and collapses it. This wastes more memory than necessary. It would be more efficient to do what #FPstudent and #coder do and generate the numbers and immediately either make them a part of the end product, or throw them away if they're divisible by 2 or 3. Two things you could do in addition to this is,
Make the function tail-recursive, so it uses less stack space.
Generalise the iteration / folding into a common pattern.
For example,
fun folditer f e i j =
if i < j
then folditer f (f (i, e)) (i+1) j
else e
fun accept i = i mod 2 <> 0 andalso i mod 3 <> 0
val f = folditer (fn (i, acc) => if accept i then i*acc else acc) 1 1
This is similar to Python's xrange.

How can you write a function that takes 'm' and 'n' then multiplies 'm', 'n' number of times?

Here is the problem: Declare type and define a function that takes 2 positive numbers (say m and n) as input, and raise m to the power of n. please use recursion only. Don’t use power operator or library function, just use recursion.
this is my code so far:
sqr :: Int -> Int -> Int
sqr m n
| m > 0 && n > 0 = sqr (m * m) (n - 1)
| otherwise = m
For some reason, when I do sqr 10 2, it gives me like 1000 or something. Does anyone know what I'm doing wrong?
Let's expand. Also, your function should be called pow, not sqr, but that is not really important.
sqr 10 2 = sqr (10 * 10) (2 - 1)
= sqr 100 1
= sqr (100 * 100) (1 - 1)
= sqr 10000 0
= 10000
This demonstrates why sqr 10 2 = 10000.
Every time you recurse, there's a different value for m. So you need to take that into account some way:
Either you write a version that works even though m has a different value each time, or,
You find a way to keep the original value of m around.
I would say that the simplest method uses the fact that m^n = m * m^(n-1), and m^0 = 1.
If you're clever, there's a method that's much faster, which also relies on the fact that m^2n = (m^n)^2.
Spoilers
Some of those mathematical formulas I wrote above are actually valid Haskell code.
import Prelude hiding ((^))
infixr 8 ^
(^) :: Int -> Int -> Int
-- Do these two lines look familiar?
m^0 = 1
m^n = m * m^(n-1)
This is just the infix version of the function. You can change the infix operator to a normal function,
pow :: Int -> Int -> Int
pow m 0 = 1
pow m n = m * pow m (n - 1)
And the faster version:
pow :: Int -> Int -> Int
pow m 0 = 1
pow m n
| even n = x * x where x = pow m (n `quot` 2)
| otherwise = m * pow m (n - 1)
There are 2 separate problems here. Just write out all the term-rewriting steps to see what they are:
sqr 10 2
sqr (10 * 10) (2 - 1)
sqr 100 (2 - 1)
sqr 100 1
sqr (100 * 100) (1 - 1)
sqr 10000 (1 - 1)
sqr 10000 0
10000
This will show you one of the problems clearly. If you don't see the other one yet, try starting with
sqr 10 3