Last digit of a huge number - haskell

I'm solving Last digit of a huge number in Codewars.
I managed to find out a way to calculate odd number ^ odd number and odd number ^ even number. However I got stuck in even ^ even/odd as the relation between the number and its power's mod is not obvious.
Here's what I managed to get:
lastDigit :: [Integer] -> Integer
lastDigit = (`rem` 10) . go
where
go [] = 1
go [x] = x
go (x : y : r)
| odd x && odd y = x ^ (go (y : r) `rem` (x + 1))
| odd x && even y = x ^ (foldMod y (go r) (x + 1))
| otherwise = -- any hint?
foldMod :: Integer -> Integer -> Integer -> Integer
foldMod _ 0 _ = 1
foldMod base 1 modulo = base `rem` modulo
foldMod base power modulo = (base * foldMod base (power -1) modulo) `rem` modulo
Can anyone give some hints on how to do about the even cases?

I recommend rethinking your approach, and beginning with a more general function. Specifically, can you compute
powMod :: Integer -> [Integer] -> Integer
where powMod base exponents computes the exponential tower described in the problem mod base? Note that when you recurse, you will recurse with a different base -- because the cycle lengths of the various first exponents are not necessarily all divisors of base. For example, in base 10, any first exponent with a last digit of 7 cycles every four goes, not every ten; the last digit of the powers goes like this:
x 0 1 2 3 4 5 6 7
7^x `mod` 10 1 7 9 3 1 7 9 3
You'll also want to watch out for situations where the first exponent is not itself in the eventual cycle that gets reached; for example, in base 4, we have:
x 0 1 2 3 4 5 6 7
2^x `mod` 4 1 2 0 0 0 0 0 0
So you can't look at just x `mod` 1 and infer from it what 2^x `mod` 4 is, even though the cycle length is 1. (There are other examples, like 2^x `mod` 12, where the cycle is longer than 1 and still doesn't have the original 2 in it.)

You do not need to calculate the entire number to know the last digit, there are fast, and less fast approaches that can calculate the last digit without having to worry about all the other digits.
A simple approach that can calculate ab in O(log b) time is by making use of the following equivalence:
(a×b) mod m = ((a mod m) × (b mod m)) mod m.
This means we can each time calculate the last digit and work with that. It thus means that as long as we can represent all numbers up to 81, we can calculate the ab mod m powMod m a b:
powMod :: Int -> Int -> Int -> Int
powMod m = go
where go _ 0 = 1
go a b | even n = r
| otherwise = (x * r) `mod` m
where r = go ((a*a) `mod` m) (div b 2) `mod` m
If we assume we can calculate modulo, divide by two, check if a value is even, etc. in constant time, this runs in O(log b).
But we can even do this faster by looking for cycles. Imagine that we have to calculate a power of 7, then 7^0 is 1, 7^1 is 7, 7^2 mod 10 = 9, etc. We can make a table with multiplications:
× │ 0 1 2 3 4 5 6 7 8 9
──┼─────────────────────
0 │ 0 0 0 0 0 0 0 0 0 0
1 │ 1 2 3 4 5 6 7 8 9
2 │ 4 6 8 0 2 4 8 6
3 │ 9 2 5 8 1 4 7
4 │ 6 0 4 8 2 6
5 │ 5 0 5 0 5
6 │ 6 2 8 4
7 │ 9 6 3
8 | 4 2
9 | 1
If we thus look at the last digit for a power of 7, we see that for:
power │ │ last digit
──────────────────────────
0 │ │ 1
1 │ 7*1 │ 7
2 │ 7*7 │ 9
3 │ 7*9 │ 3
4 │ 7*3 │ 1
This thus means that there is a cycle, indeed, after each multiplication with 7, we move to the next state, and thus obtain the following graph:
1 → 7 → 9 → 3
↖_______________/
This thus means that the cycle has a length of four. It thus means that if we have to calculate 7 to the power of for example 374, then we know that these are 93 cycles of length four that have thus no impact, and two extra moves, we thus know that the last digit of 7393 is 9, without having to compute this number. Since such cycles has a maximum length of 10, this can thus done in constant time do determine the last digit of the decimal number.

Related

Print values and it's associated index when working with vectors / matrix in J

If I want to check how many values in a vector or matrix are less than a given value
I can use +/ (a < 20). But what if I wanted to know both the specific value and it's index.
Something like (2(value) 5(index)) as a table. I looked at i., i: (which give first and last position) and I. Does sorting first help?
A very common pattern in J is the creation of a mask from a filter and applying an action on and/or using the masked data in a hook or fork:
((actions) (filter)) (data)
For example:
NB. Random array
a =: ? 20 $ 10
6 3 9 0 3 3 0 6 2 9 2 4 6 8 7 4 6 1 7 1
NB. Filter and mask
f =: 5 < ]
m =: f a
1 0 1 0 0 0 0 1 0 1 0 0 1 1 1 0 1 0 1 0
NB. Values of a on m
m # a
6 9 6 9 6 8 7 6 7
NB. Indices of a on m
I. m
0 2 7 9 12 13 14 16 18
NB. Joint results
(I.m) ,: (m # a)
0 2 7 9 12 13 14 16 18
6 9 6 9 6 8 7 6 7
In other words, in this case you have m&# and f acting on a and I. acting on m. Notice that the final result can be derived from an action on m alone by commuting the arguments of copy #~:
(I. ,: (a #~ ]) m
0 2 7 9 12 13 14 16 18
6 9 6 9 6 8 7 6 7
and a can be pulled out from the action on m like so:
a ( (]I.) ,: (#~ ])) m
But since m itself is derived from an action (f) on a, we can write:
a ( (]I.) ,: (#~ ])) (f a)
which is a simple monadic hook y v (f y) → (v f) y.
Therefore:
action =: (]I.) ,: (#~ ])
filter =: 5 < ]
data =: a
(action filter) data
0 2 7 9 12 13 14 16 18
6 9 6 9 6 8 7 6 7

All list items up to, and including, the first repeated item

Consider:
x =. 0 1 2 3 4 1 3 4 99
v =. [ {.~ (>: # i.&1 # (##~. = #\))
v x NB. => 0 1 2 3 4 1
The behavior is correct. But as you can see, v is shamefully verbose. Is there a better solution?
You want the monad ~: (nub sieve):
v =: {.~ 1 + 0 i.~ ~:
x =: 0 1 2 3 4 1 3 4 99
v x
0 1 2 3 4 1
Code review:
Outside code-golf contexts, don't use #\ in place of i.##. It's too cutesy, hard to maintain, and won't be recognized by the special-code optimizer.
Don't assign to the names x, y, u, v, m, or n (except in special circumstances, and always locally in an explicit context).

Python Modulo Function

I understand that the Modulo function returns the remainder of a division problem.
Ex: 16 % 5 = 3 with a remainder of 1. So 1 would be returned.
>>> 1 % 3 Three goes into 1 zero times remainder 1
1
>>> 2 % 3 Three goes into 2 zero times remainder 2
2
>>> 0 % 3 What happens here? 3 goes into zero, zero times remainder 3
if we follow the logic of the previous two illustrations, that is not what was returned, zero was. Why?
>>> 0 % 3
0
The Python % operator is defined so that x % y == x - (x // y) * y, where x // y = ⌊x / y⌋. For positive integers, this corresponds to the usual notion of the “remainder” of a division. So, for any y ≠ 0,
0 % y
= 0 - ⌊0 / y⌋ * y by definition of %
= 0 - ⌊0⌋ * y because 0 divided by anything is 0
= 0 - 0 * y because 0 is an integer, so floor leaves it unchanged
= 0 - 0 because 0 times anything is 0
= 0
Look at it again:
1 % 3 is 0 remainder 1 => 1 = 3*0 + 1
2 % 3 is 0 remainder 2 => 2 = 3*0 + 2
0 % 3 is 0 remainder 0 [not 3] because 0 = 3*0 + 0
why are you taking what remains after the division in the first two cases but not the last?

FoldList like primitive in J

Mathematica has a built-in function called FoldList FoldList function description. Is there a similar primitive verb in J?
(I know that J has a ^: verb, which is like Nest and FixedPoint.)
To clarify my question, J has dyadic verb, so usually u / x1 x2 x3 becomes x1 u (x2 u x3), which works just like FoldList, with reverse order.
Except if the function u takes y, in a different shape from x. In FoldList there is an initial x. In J, if x3 is a different shape, one has to rely on < to pack it together. For example, one has to pack and unpack
[list =. (;/ 3 3 4 3 3 34),(< 1 2)
+-+-+-+-+-+--+---+
|3|3|4|3|3|34|1 2|
+-+-+-+-+-+--+---+
tf =: 4 : '<((> x) , >y)'
tf/ list
+----------------+
|1 2 3 3 4 3 3 34|
+----------------+
tf/\ |. list
+---+------+--------+----------+------------+--------------+----------------+
|1 2|1 2 34|1 2 34 3|1 2 34 3 3|1 2 34 3 3 4|1 2 34 3 3 4 3|1 2 34 3 3 4 3 3|
+---+------+--------+----------+------------+--------------+----------------+
which is kind of inconvenient. Any better solutions?
u/\ comes very close (if you don't mind the right folding):
+/\ 1 2 3 4
1 3 6 10
*/\1+i.10
1 2 6 24 120 720 5040 ...
(+%)/\7#1. NB. continued fraction of phi
1 2 1.5 1.66667 1.6 1.625 1.61538
edit on your edit:
The first two elements of FoldList are x and f(x,a). In J those two have to be of the same "kind" (shape+type) if you want them on the same list. The inconvenience comes from J's data structures not from the lack of a FoldList verb. If you exclude x from the list, things are easier:
FoldListWithout_x =: 1 : 'u/ each }.<\y'
; FoldListWithout_x 1 2 3 4
┌─────┬───────┬─────────┐
│┌─┬─┐│┌─┬─┬─┐│┌─┬─┬─┬─┐│
││1│2│││1│2│3│││1│2│3│4││
│└─┴─┘│└─┴─┴─┘│└─┴─┴─┴─┘│
└─────┴───────┴─────────┘
>+ FoldListWithout_x 1 2 3 4
3 6 10
(+%) FoldListWithout_x 7#1
┌─┬───┬───────┬───┬─────┬───────┐
│2│1.5│1.66667│1.6│1.625│1.61538│
└─┴───┴───────┴───┴─────┴───────┘
The next logical step is to include a boxed x after making the folds, but that will either require more complex code or a case-by-case construction. Eg:
FoldList =: 1 :'({.y) ; u FoldListWithout_x y'
+ FoldList 1 2 3 4
┌─┬─┬─┬──┐
│1│3│6│10│
└─┴─┴─┴──┘
; FoldList 1 2 3 4
┌─┬─────┬───────┬─────────┐
│1│┌─┬─┐│┌─┬─┬─┐│┌─┬─┬─┬─┐│
│ ││1│2│││1│2│3│││1│2│3│4││
│ │└─┴─┘│└─┴─┴─┘│└─┴─┴─┴─┘│
└─┴─────┴───────┴─────────┘
vs
FoldList =: 1 :'(<{.y) ; u FoldListWithout_x y'
+ FoldList 1 2 3 4
┌───┬─┬─┬──┐
│┌─┐│3│6│10│
││1││ │ │ │
│└─┘│ │ │ │
└───┴─┴─┴──┘
; FoldList 1 2 3 4
┌───┬─────┬───────┬─────────┐
│┌─┐│┌─┬─┐│┌─┬─┬─┐│┌─┬─┬─┬─┐│
││1│││1│2│││1│2│3│││1│2│3│4││
│└─┘│└─┴─┘│└─┴─┴─┘│└─┴─┴─┴─┘│
└───┴─────┴───────┴─────────┘
I guess #Dan Bron's comment deserves an answer. It is discussed with some solutions in http://www.jsoftware.com/pipermail/programming/2006-May/002245.html
if we define an adverb (modified from the link above)
upd =: 1 : 0
:
u&.> /\ ( <"_ x),<"0 y
)
then
1 2 , upd |. 3 3 4 3 3 34
┌───┬──────┬────────┬──────────┬────────────┬──────────────┬────────────────┐
│1 2│1 2 34│1 2 34 3│1 2 34 3 3│1 2 34 3 3 4│1 2 34 3 3 4 3│1 2 34 3 3 4 3 3│
└───┴──────┴────────┴──────────┴────────────┴──────────────┴────────────────┘

operator precedence in Haskell

I am confused about the rules for operator precedence in Haskell.
More specifically, why is this:
*Main> 2 * 3 `mod` 2
0
different than this?
*Main> 2 * mod 3 2
2
Function calls bind the tightest, and so
2 * mod 3 2
is the same as
2 * (mod 3 2)
Keep in mind that mod is not being used as an operator here since there are no backticks.
Now, when mod is used in infix form it has a precedence of 7, which (*) also has. Since they have the same precendence, and are left-associative, they are simply parsed from left to right:
(2 * 3) `mod` 2
2*3 = 6 and then mod 2 = 3 with no remainder ... so 6 mod 2 = 0 is your answer there.
In your second case you are doing 2 * the result of mod 3 2 which is 2 * 1 = 2. Therefore your answer is 2.... Your operator precedence remains the same, you just arranged it so the answers were expressed accordingly.

Resources