Haskell - Trying to create a function to find the factorial of odd numbers - function

fact :: Int -> Int
fact n
|n < 0 = 0
|n == 0 = 1
|n > 0 && n `mod` 2 == 1 = fact (n-1) * n
|n > 0 && n `mod` 2 == 0 = n-1
When I enter an odd number for example: fact 5 will give 15, as it should 1 * 3 * 5 = 15. However I realized that if I do fact 7 or any other odd number, it only multiplies the first two odd numbers. How do I get the function to multiply all the odd numbers and not just the first 2. Eg. fact 7 = 35 (ie. 3 * 5). Also note, that if an even number is entered, it will work out the factorial of all the odd numbers up until and not including the even number.

This reminds me of the famous Evolution of a Haskell Programmer. Paraphrasing the tenured professor's answer:
factorialOfOdds :: Integer -> Integer
factorialOfOdds n = product [1,3..n]

You're problem is that your case for an even number is n-1, which means that when you get to an odd number you're really just doing
n * (n - 1 - 1)
When what you want is
n * n-2 * n-4 ...
So try this instead
fact :: Integer -> Integer -- Overflows
fact n
|n < 0 = 0
|n == 0 || n == 1 = 1
|n `mod` 2 == 1 = fact (n-2) * n
|n `mod` 2 == 0 = fact (n-1)
I also took the liberty of removing some redundant logic. Here we decrement by two if it's odd, so 5 -> 3. And in the even case we decrement by one to end up on an odd number and that recurse on that.

Related

Finding the location of ones in a bit mask - Julia

I have a series of values that are each being stored as UInt16. Each of these numbers represents a bitmask - these numbers are commands that have been sent to a microprocessor telling it which pins to set high or low. I would like to parse this arrow of commands to find out which pins were being set high each time in such a way that is easier to analyse later.
Consider the example value 0x3c00, which in decimal is 15360 and in binary is 0011110000000000. Currently I have the following function
function read_message(hex_rep)
return findall.(x -> x .== '1',bitstring(hex_rep))
end
Which gets called on every element of the array of UInt16. Is there a better/more efficient way of doing this?
The best approach probably depends on how you want to handle vectors of hex-values. But here's an approach for processing a single hex which is much faster than the one in the OP:
function readmsg(x::UInt16)
N = count_ones(x)
inds = Vector{Int}(undef, N)
if N == 0
return inds
end
k = trailing_zeros(x)
x >>= k + 1
i = N - 1
inds[N] = n = 16 - k
while i >= 1
(x, r) = divrem(x, 0x2)
n -= 1
if r == 1
inds[i] = n
i -= 1
end
end
return inds
end
I can suggest padding your vector into a Vector{UInt64} and use that to manually construct a BitVector. The following should mostly work (even for input element types other than UInt16), but I haven't taken into account specific endianness you might want to respect:
julia> function read_messages(msgs)
bytes = reinterpret(UInt8, msgs)
N = length(bytes)
nchunks, remaining = divrem(N, sizeof(UInt64))
padded_bytes = zeros(UInt8, sizeof(UInt64) * cld(N, sizeof(UInt64)))
copyto!(padded_bytes, bytes)
b = BitVector(undef, N * 8)
b.chunks = reinterpret(UInt64, padded_bytes)
return b
end
read_messages (generic function with 1 method)
julia> msgs
2-element Vector{UInt16}:
0x3c00
0x8000
julia> read_messages(msgs)
32-element BitVector:
0
0
0
0
0
0
0
0
0
⋮
0
0
0
0
0
0
0
1
julia> read_messages(msgs) |> findall
5-element Vector{Int64}:
11
12
13
14
32
julia> bitstring.(msgs)
2-element Vector{String}:
"0011110000000000"
"1000000000000000"
(Getting rid of the unnecessary allocation of the undef bit vector would require some black magic, I belive.)

OCaml : recursive function dealing with parity between list elements and an int

This function should take two arguments a list and an int. if an element of the list and the number “a” parity is equal then they’d have to be summed, else the two numbers should be subtracted.
The calculation should be done in this order :
At the beginning, the residual value r is the value of a,
Each element e of lst (taken in the order given by the list) affects the residual value: if e and r are of the same parity (both odd or both even) then the new r’ is equal to the sum of r + e, if not then it should be equal to the subtraction of r - e,
The last r is the result expected.
To put this into an example:
par [4;7;3;6] 5
should return -1, it would work as follows :
5 and 4 have a different parity so we subtract -> 5 - 4 = 1
1 and 7 are both odd, so we add them together -> 1 + 7 = 8
8 and 3 have a different parity -> 8 - 3 = 5
Finally, 5 and 6 have different parity -> 5 - 6 = -1
I have thought of something like this below :
let rec par lst a =
match lst with
| [] -> 0
| h::t -> if (h mod 2 == 0 && a mod 2 == 0) || (h mod 2 == 1 && a mod 2 == 1) then a + h
| h::t -> if (h mod 2 == 0 && a mod 2 == 1) || (h mod 2 == 1 && a mod 2 == 0) then a - h :: par t a ;;
EDIT1 : Here is the error I get from the compiler :
Line 4, characters 83-88: Error: This expression has type int but an
expression was expected of type unit because it is in the result of a
conditional with no else branch
The idea is to build this function using no more than the following predefined functions List.hd, List.tl et List.length.
What is disturbing in my proposition above and how to remediate it? Anyone can help me resolve this, please?
EDIT 2:
I was able to do what is needed with if...then... else syntax (not the best I know for OCaml) but I personally have more difficulties sometimes understanding the pattern matching. Anyhow here's what I got :
let rec par lst a = (* Sorry it might hurt some sensible eyes *)
if List.length lst = 0 then a
else
let r = if (List.hd lst + a) mod 2 == 0 then (a + (List.hd lst))
else (a - (List.hd lst)) in
par (List.tl lst) r ;;
val par : int list -> int -> int = <fun>
Suggestions and help to put it into a pattern-matching syntax are welcomed.
Your code doesn't compile. Did you try compiling it? Did you read the errors and warnings produced by the compiler? Could you please add them to your question?
A few comments about your code:
| h::t -> if ... then ... should be | h::t when ... -> ...;
(h mod 2 == 0 && a mod 2 == 0) || (h mod 2 == 1 && a mod 2 == 1) can be simplified to (h - a) mod 2 == 0;
The compiler likes to know that the matching was exhaustive; in particular, you don't need to repeat the test in the third line of the matching (the third line will only be read if the test was false in the second line);
You are missing the recursive call in the second line of the matching;
In the third line of the matching, you are returning a list rather than a number (the compiler should have explicitly told you about that type mismatch!! did you not read the compiler error message?);
In the first line of the matching, in case the list is empty, you return 0. Are you sure that 0 is the value you want to return, when you've reached the end of the list? What about the residual value that you have calculated?
Once you have fixed this version of your code as a recursive function, I recommend trying to write a code solving the same problem using List.fold_left, rather than List.hd and List.tl as you are suggesting.
When I first wrote my answer, I included a fixed version of your code, but I think I'd be doing you a disservice by handing out the solution rather than letting you figure it out.

How many binary numbers with N bits if no more than M zeros/ones in a row

Is there an equation I can use for arbitrary M and N?
Example, N=3 and M=2:
3 bits allow for 8 different combinations, but only 2 of them do not contain more than 2 same symbols in a row
000 - Fails
001 - Fails
010 - OK
011 - Fails
100 - Fails
101 - OK
110 - Fails
111 - Fails
One way to frame the problem is as follows: we would like to count binary words of length n without runs of length m or larger. Let g(n, m) denote the number of such words. In the example, n = 3 and m = 2.
If n < m, every binary word works, and we get g(n, m) = 2^n words in total.
When n >= m, we can choose to start with 1, 2, ... m-1 repeated values,
followed by g(n-1, m), g(n-2, m), ... g(n-m+1, m) choices respectively. Combined, we get the following recursion (in Python):
from functools import lru_cache
#lru_cache(None) # memoization
def g(n, m):
if n < m:
return 2 ** n
else:
return sum(g(n-j, m) for j in range(1, m))
To test for correctness, we can compute the number of such binary sequences directly:
from itertools import product, groupby
def brute_force(n, k):
# generate all binary sequences of length n
products = product([0,1], repeat=n)
count = 0
for prod in products:
has_run = False
# group consecutive digits
for _, gp in groupby(prod):
gp_size = sum(1 for _ in gp)
if gp_size >= k:
# there are k or more consecutive digits in a row
has_run = True
break
if not has_run:
count += 1
return count
assert 2 == g(3, 2) == brute_force(3, 2)
assert 927936 == g(20, 7) == brute_force(20, 7)

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

Binary divisibility by 10

How to check if a binary number can be divided by 10 (decimal), without converting it to other system.
For example, we have a number:
1010 1011 0100 0001 0000 0100
How we can check that this number is divisible by 10?
First split the number into odd and even bits (I'm calling "even" the
bits corresponding to even powers of 2):
100100110010110000000101101110
0 1 0 1 0 0 1 0 0 0 1 1 0 1 0 even 1 0 0 1 0 1 1 0 0 0 0 0 1 1 1 odd
Now in each of these, add and subtract the digits alternately, as in
the standard test for divisibility by 11 in decimal (starting with
addition at the right):
100100110010110000000101101110 +0-1+0-1+0-0+1-0+0-0+1-1+0-1+0 =
-2 +1-0+0-1+0-1+1-0+0-0+0-0+1-1+1 = 1
Now double the sum of the odd digits and add it to the sum of the even
digits:
2*1 + -2 = 0
If the result is divisible by 5, as in this case, the number itself is
divisible by 5.
Since this number is also divisible by 2 (the rightmost digit being
0), it is divisible by 10.
Link
If you are talking about computational methods, you can do a divisiblity-by-5 test and a divisibility-by-2 test.
The numbers below assume unsigned 32-bit arithmetic, but can easily be extended to larger numbers.
I'll provide some code first, followed by a more textual explanation:
unsigned int div5exact(unsigned int n)
{
// returns n/5 as long as n actually divides 5
// (because 'n * (INV5 * 5)' == 'n * 1' mod 2^32
#define INV5 0xcccccccd
return n * INV5;
}
unsigned int divides5(unsigned int n)
{
unsigned int q = div5exact(n);
if (q <= 0x33333333) /* q*5 < 2^32? */
{
/* q*5 doesn't overflow, so n == q*5 */
return 1;
}
else
{
/* q*5 overflows, so n != q*5 */
return 0;
}
}
int divides2(unsigned int n)
{
/* easy divisibility by 2 test */
return (n & 1) == 0;
}
int divides10(unsigned int n)
{
return divides2(n) && divides5(n);
}
/* fast one-liner: */
#define DIVIDES10(n) ( ((n) & 1) == 0 && ((n) * 0xcccccccd) <= 0x33333333 )
Divisibility by 2 is easy: (n&1) == 0 means that n is even.
Divisibility by 5 involves multiplying by the inverse of 5, which is 0xcccccccd (because 0xcccccccd * 5 == 0x400000001, which is just 0x1 if you truncate to 32 bits).
When you multiply n*5 by the inverse of 5, you get n * 5*(inverse of 5), which in 32-bit math simplifies to n*1 .
Now let's say n and q are 32-bit numbers, and q = n*(inverse of 5) mod 232.
Because n is no greater than 0xffffffff, we know that n/5 is no greater than (232-1)/5 (which is 0x33333333). Therefore, we know if q is less than or equal to (232-1)/5, then we know n divides exactly by 5, because q * 5 doesn't get truncated in 32 bits, and is therefore equal to n, so n divides q and 5.
If q is greater than (232-1)/5, then we know it doesn't divide 5, because there is a one-one mapping between the 32-bit numbers divisible by 5 and the numbers between 0 and (232-1)/5, and so any number out of this range doesn't map to a number that's divisible by 5.
Here is the code in python to check the divisibilty by 10 using bitwise technique
#taking input in string which is a binary number eg: 1010,1110
s = input()
#taking initial value of x as o
x = 0
for i in s:
if i == '1':
x = (x*2 + 1) % 10
else:
x = x*2 % 10
#if x is turn to be 0 then it is divisible by 10
if x:
print("Not divisible by 10")
else:
print("Divisible by 10")