multiplicative inverse? [closed] - security

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I know that an affine cipher substitutes BD with SG. I need to find the encryption formula, in the form y = a x + b, where a and b are coefficients.
From the information above I end up having to equations:
a+b=18 and
3a+b=6
So I am working like this:
a+b=18 and 3a + b = 6-> 3a+18-a=6->  2a= 6-18 -> 2a=14 (as it is mod 26)
b=18-a
2a=? 
So, O want to multiply by the multiplicative inverse of 2 mod 26
I can't find a multiplicative inverse of number 2 with 26 (y = ax + b mod 26)
Can anyone please help me find a and b?

That's because 2 doesn't have a multiplicative inverse mod 26: since 13*2=0, there does not exist K such that K * a = 1. Your modulus must be prime. Try looking up the Chinese Remainder Theorem for more information.
To be more specific, integers mod 26 is not a field (a mathematical set where every element, except 0, has a multiplicative inverse). Any ring in which a * b = 0, for some a!=0 and b!=0, is not a field.
In fact, a field will always have p^n elements, where p is a prime number and n is a positive integer. The simplest fields are just integers mod a prime number, but for prime powers you need to construct a more elaborate system. So, in short, use a different modulus like 29.

Does a = 7 work? 2*7 = 14. Thus, b = 11.
Let's check the 2 equations to see if that works:
7+11 = 18 (check for the first equation).
3*7+11=21+11 = 32 = 6.
What is wrong with the above?
EDIT: Ok, now I see what could go wrong with trying to do a division by 2 in a non-prime modulus as it is similar to a division by 0. You could take ribond's suggestion of using the Chinese Remainder Theorem and split the equations into another pair of pairs:
mod 13: a+b=5, 3a+b=6. (2a = 1 = 14 => a=7. b = 18-7 = 11.)
mod 2: a+b=0. 3a+b=0 (Note this is the same equation and has a pair of possible solutions where a and b are either 0 or 1.)
Thus there is the unique solution for your problem I think.

Other posters are right in that there is no inverse of 2 modulo 26, so you can't solve 2a=14 mod 26 by multiplying through by the inverse of 2. But that doesn't mean that 2a=14 mod 26 isn't solvable.
Consider the general equation cx = d mod n (c=2,d=14,n=26 in your case). Let g = gcd(c,n). The equation cx=d has a solution if an only if g divides d. If g divides d, then there are in fact multiple solutions (g of them). The equation (c/g)x = d/g mod n/g has a unique solution (call it x_0) because c/g is relatively prime to n/g and therefore has an inverse. The solutions to the original equation are x_0, x_0 + n/g, ..., x_0 + (g-1)n/g.
In your case c=2,d=14,n=26, and g=2. g divides d, so first solve the equation (2/2)x = (14/2) mod (26/2) which gives 7. So both 7 and 7+13=20 solve your original equation.
Note that this means you haven't uniquely determined your affine transformation, two possibilities still exist. You need another data point...

Related

Sum of arrays with repeated indices

How can I add an array of numbers to another array by indices? Especially with repeated indices. Like that
x
1 2 3 4
idx
0 1 0
y
5 6 7
] x add idx;y NB. (1 + 5 + 7) , (2 + 6) , 3 , 4
13 8 3 4
All nouns (x, idx, y) can be millions of items and I need to fast 'add' verb.
UPDATE
Solution (thanks to Dan Bron):
cumIdx =: 1 : 0
:
'i z' =. y
n =. ~. i
x n}~ (n{x) + i u//. z
)
(1 2 3 4) + cumIdx (0 1 0);(5 6 7)
13 8 3 4
For now, a short answer in the "get it done" mode:
data =. 1 2 3 4
idx =. 0 1 0
updat =. 5 6 7
cumIdx =: adverb define
:
n =. ~. m
y n}~ (n{y) + m +//. x
)
updat idx cumIdx data NB. 13 8 3 4
In brief:
Start by grouping the update array (in your post, y¹) where your index array has the same value, and taking the sum of each group
Accomplish this using the adverb key (/.) with sum (+/) as its verbal argument, deriving a dyadic verb whose arguments are idx on the left and the update array (your y, my updat) on the right.
Get the nub (~.) of your index array
Select these (unique) indices from your value array (your x, my data)
This will, by definition, have the same length as the cumulative sums we calculated in (1.)
Add these to the cumulative sum
Now you have your final updates to the data; updat and idx have the same length, so you just merge them into your value array using }, as you did in your code
Since we kept the update array small (never greater than its original length), this should have decent performance on larger inputs, though I haven't run any tests. The only performance drawback is the double computation of the nub of idx (once explicitly with ~. and once implicitly with /.), though since your values are integers, this should be relatively cheap; it's one of J's stronger areas, performance-wise.
¹ I realize renaming your arrays makes this answer more verbose than it needs to be. However, since you named your primary data x rather than y (which is the convention), if I had just kept your naming convention, then when I invoked cumIdx, the names of the nouns inside the definition would have the opposite meanings to the ones outside the definition, which I thought would cause greater confusion. For this reason, it's best to keep "primary data" on the right (y), and "control data" on the left (x).You might also consider constraining your use of the special names x,y,u,v,m and n to where they're already implicitly defined by invoking an explicit definition; definitely never change their nameclasses.
This approach also uses key (/.) but is a bit more simplistic in its approach.
It is likely to use more space especially for big updates than Dan Bron's.
addByIdx=: {{ (m , i.## y) +//. x,y }}
updat idx addByIdx data
13 8 3 4

recursive exponentiator output and complexity

def exp3(a,b):
if b == 1:
return a
if (b%2)*2 == b:
return exp3(a*a, b/2)
else: return a*exp3(a,b-1)
This is a recursive exponentiator program.
Question 1:
If b is even, it will exceute (b%2)2 == b. If b is odd, it will exceute aexp3(a,b-1). There is no problem in my program. If b is 4, (4%2)*2=0, and 0 is not equal to b. So I can't understand how to calculate b when it's even.
Question 2:
I want to calucate the number of steps in the program. so according to my textbook, I can get the formual as follows.
b even t(b) = 6 + t(b/2)
b odd t(b) = 6 + t(b-1)
Why is the first number 6? How can I get the number 3 in the beginning?
Your (b%2)*2 == b test is never true. I think you want b % 2 == 0 to test if b is even. The code still gets the right answer because the other recursive case (intended only for odd b values) works for even ones too (it's just less efficient).
As for your other question, I have no idea where the 6 is coming from either. It depends a lot on what you're counting as a "step". Usually it's most useful to discuss performance in terms of "Big-O" values rather than specific numbers.

Compare two numbers in Haskell [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
http://i.stack.imgur.com/71w9v.png
I have to find how much money a player wins.
This must be done by creating a function called digits Int->Int->Int. For example if the first input is 13758455 and the second input of the function is 13758455 then I should get 1000000 in the compiler.
This is normally an easy task in Java but I wasn't able to find something like a counter to count up as I find more digits in a number.
As there is no state in Haskell, you cannot have counters like you would in imperative languages.
You will often use recursion for this matter. Here is an example:
module Main where
moneyWon :: Int -> Int
moneyWon 8 = 1000000
moneyWon 7 = 100000
moneyWon 6 = 8000
moneyWon 5 = 300
moneyWon 4 = 20
moneyWon 3 = 5
moneyWon 2 = 1
moneyWon _ = 0
digits :: Int -> Int -> Int
digits 0 0 = 0
digits x y = digits dx dy + if mx == my then 1 else 0
where (dx, mx) = divMod x 10
(dy, my) = divMod y 10
main = do
print $ (moneyWon . digits 12345678) 12345668
Notes:
counting corresponding digits and evaluating the prize are two different concerns, that's why I've separated them
the divMod x 10 is a way to get the lowest meaning digit in base 10
in real life, you should not use an integer to hold the digits since it is more a list matter than a number matter (that's why the number starts at 10000000 and not at 0, forcing the user to enter the right number of digits).
Using Int leaves with the task to check the number is valid.

"Consolidation" algorithm name / implementation

Not quite sure how to describe this, but I have a word game I like to play that I'd like to implement as a computer program.
The basic gist is that you look at the values of the letters (A=1..Z=26), and consolidate the letters into the fewest possible, and that are the closest possible to each other.
As an example:
s t a c k
Sum the values
19 + 20 + 1 + 3 + 11 = 54
Find the fewest number of letters:
ceil(54/26) = 3
Choose letters closest to each other
54/3 = 18
Letters to be displayed should be rrr.
That happens to be an easy example. What would it look like when you need to have, say, rrs (if your initial string was 'a stack' instead)?
Does this already have a name that I can lookup and implement?
I think your problem boils down to this: given n and k, find numbers r1, r2, ..., rk such that sum(r1 + r2 + ... + rk) = n and max(r1, r2, ..., rk) - min(r1, r2, ..., rk) is as small as possible.
The solution is pick r = floor(n / k), and set n mod k of the numbers to be r + 1, and the rest r.
For example, if n = 55 and k = 3 (your example), we have floor(55/3) = 18 and 55 mod 3 is 1, so the solution is 19, 18, 18.
All that remains is converting between numbers and letters.

Need Hint for ProjectEuler Problem

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I could easily brute force the solution in an imperative programming language with loops. But I want to do this in Haskell and not having loops makes it much harder. I was thinking of doing something like this:
[n | n <- [1..], d <- [1..20], n `mod` d == 0] !! 0
But I know that won't work because "d" will make the condition equal True at d = 1. I need a hint on how to make it so that n mod d is calculated for [1..20] and can be verified for all 20 numbers.
Again, please don't give me a solution. Thanks.
As with many of the Project Euler problems, this is at least as much about math as it is about programming.
What you're looking for is the least common multiple of a set of numbers, which happen to be in a sequence starting at 1.
A likely tactic in a functional language is trying to make it recursive based on figuring out the relation between the smallest number divisible by all of [1..n] and the smallest number divisible by all of [1..n+1]. Play with this with some smaller numbers than 20 and try to understand the mathematical relation or perhaps discern a pattern.
Instead of a search until you find such a number, consider instead a constructive algorithm, where, given a set of numbers, you construct the smallest (or least) positive number that is evenly divisible by (aka "is a common multiple of") all those numbers. Look at the algorithms there, and consider how Euclid's algorithm (which they mention) might apply.
Can you think of any relationship between two numbers in terms of their greatest common divisor and their least common multiple? How about among a set of numbers?
If you look at it, it seems to be a list filtering operation. List of infinite numbers, to be filtered based on case the whether number is divisible by all numbers from 1 to 20.
So what we got is we need a function which takes a integer and a list of integer and tells whether it is divisible by all those numbers in the list
isDivisible :: [Int] -> Int -> Bool
and then use this in List filter as
filter (isDivisible [1..20]) [1..]
Now as Haskell is a lazy language, you just need to take the required number of items (in your case you need just one hence List.head method sounds good) from the above filter result.
I hope this helps you. This is a simple solution and there will be many other single line solutions for this too :)
Alternative answer: You can just take advantage of the lcm function provided in the Prelude.
For efficiently solving this, go with Don Roby's answer. If you just want a little hint on the brute force approach, translate what you wrote back into english and see how it differs from the problem description.
You wrote something like "filter the product of the positive naturals and the positive naturals from 1 to 20"
what you want is more like "filter the positive naturals by some function of the positive naturals from 1 to 20"
You have to get Mathy in this case. You are gonna do a foldl through [1..20], starting with an accumulator n = 1. For each number p of that list, you only proceed if p is a prime. Now for the previous prime p, you want to find the largest integer q such that p^q <= 20. Multiply n *= (p^q). Once the foldl finishes, n is the number you want.
A possible brute force implementation would be
head [n|n <- [1..], all ((==0).(n `mod`)) [1..20]]
but in this case it would take way too long. The all function tests if a predicate holds for all elements of a list. The lambda is short for (\d -> mod n d == 0).
So how could you speed up the calculation? Let's factorize our divisors in prime factors, and search for the highest power of every prime factor:
2 = 2
3 = 3
4 = 2^2
5 = 5
6 = 2 * 3
7 = 7
8 = 2^3
9 = 3^2
10 = 2 * 5
11 = 11
12 = 2^2*3
13 = 13
14 = 2 *7
15 = 3 * 5
16 = 2^4
17 = 17
18 = 2 * 3^2
19 = 19
20 = 2^2 * 5
--------------------------------
max= 2^4*3^2*5*7*11*13*17*19
Using this number we have:
all ((==0).(2^4*3^2*5*7*11*13*17*19 `mod`)) [1..20]
--True
Hey, it is divisible by all numbers from 1 to 20. Not very surprising. E.g. it is divisible by 15 because it "contains" the factors 3 and 5, and it is divisible by 16, because it "contains" the factor 2^4. But is it the smallest possible number? Think about it...

Resources