The way of thinking in multiply 2 natural numbers (problem solving”) - algorithm

Prove the correctness of the following recursive algorithm to multiply two natural numbers, for all integer constants c ≥ 2.
function multiply(y,z) comment Return the product yz.
1. if z = 0 then return(0) else
2. return(multiply(cy, z/c) + y · (z mod c))
I saw this algorithm in “Algorithm Design Manual”.
I know why it works correctly, but I want to know how this algorithm came to be. Is that a good way to think of multiply two natural number with a constant c?

(multiply(cy, z/c) + y · (z mod c))
When c is the base of your representation (like decimal), then this is how multiplication can be done "manually". It's the "shift and add" method.
In c-base cy is a single shift of y to the left (i.e. adding a zero at the right); and z/c is a single shift of z to the right: the right most digit is lost.
That lost digit is actually z mod c, which is multiplied with y separately.
Here is an example with c = 10, where the apostrophe signifies the value of variables in a recursive call.
We perform the multiplication with y for each separate digit of z (retrieved with z mod c). Each next product found in this way is written shifted one more place to the left. Usually the 0 is not padded at the right of this shifted product, but it is silently assumed:
354 y
x 29 z
----
3186 y(z mod c) = 354·9 = 3186
+ 708 y'(z' mod c) = yc(z/c mod c) = 3540·2 = 7080
------
10266
So the algorithm just relies on the mathematical basis for this "shift and add" method in a given c-base.

Related

Prolog, check divisibility in Peano arithmetic

I need to check if first given term (for example s(s(nul)) (or 2)) is dividable by the second term, (for example s(nul) (or 1)).
What I want to do is multiply given term by two and then check if that term is smaller or equal to the other term (if it is equal - problem is solved).
So far I got this:
checkingIfDividable(X,X).
checkingIfDividable(X,Y) :-
X > Y,
multiplication(X,Y).
/* multiplication by two should occur here.
I can't figure it out. This solution does not work!*/
multiplication(Y):-
YY is Y * 2,
checkingIfDividable(X,YY).
I can't seem to figure out how to multiply a term by 2. Any ideas?
If a = n*b, n > 0, it is also a = n*b = (1+m)*b = b + m*b, m >= 0.
So if a is dividable by b, and a = b+x, then x is also dividable by b.
In Peano encoding, n = 1+m is written n = s(m).
Take it from here.

Right-angled triangle prolog construction

I'm to ask a question, which answers are solving this task:
Which right-angled triangles can be constructed by choosing three sides out of six segments of length being integers from 1 to 6
So, I'm thinking this is essential:
between(1,6,X),
between(1,6,Y),
between(1,6,Z),
Then we have to make sure it fits Pythagoras statement, so I'm trying this, adding to the above sentence:
(X^2 = Y^2 + Z^2 ;
Y^2 = X^2 + Z^2 ;
Z^2 = X^2 + Y^2)
Also I have been trying to replace X^2 with X*X, but it returns false every time. Why is that?
From my understanding, I need it to work like this:
Choose three sides from range 1-6, and make sure they fit Pythagoras statement. (Is triangle disparity also required here? I mean X>Y+Z,Y>X+Z,Z>X+Y ?
Check the prolog manual regarding the different comparators, etc. They mean and do various things. =:=/2 is specifically evaluates arithmetic expressions on either side and checks for equality of results. =/2 is not an equality operator; it performs prolog unification. It's important to know the difference. In your example, limiting all results to maximum of 6, then permutations of 3,4,5 are the only positive integer solutions to the right triangle.
?- between(1,6,X), between(1,6,Y), between(1,6,Z), Z^2 =:= X^2 + Y^2.
X = 3,
Y = 4,
Z = 5 ;
X = 4,
Y = 3,
Z = 5 ;
false.

Calculating product by addition

This is an algorithm question that I've been struggling with. I figured I could get some insight here. I need to make the following function in Haskell:
Declare the type and define a function that takes two numbers as input and finds their product by addition. That is, add the first number, as many times as second number, to itself.
My problem is that this is basically just multiplying two numbers together, but it says that I need to do it with addition. Does anyone have any clue on how to do this?
This is all I can come up with (it's not right): (x + x) * y
Thank you
if a is the first number and b the second
sum $ take a $ cycle [b]
should do ot
mult (x, y):
sum = 0
for 1 to y:
sum = sum + x
return sum
This is just the algorithm. I do not know Haskell. So the lambda expression in the other answer may be more appropriate. Also, I use an intermediate variable.
PS: forget the previous embarrassing recursive algorithm
Work it out by induction.
We know the answer to one simple (the simplest) problem: multiplying anything by 0 yields 0. So we write:
mul x 0 = 0
Now, the inductive step: we can build a solution to a bigger problem, if we know a solution to the smaller problem; that way we can always reduce any big problem to the smallest problem, for which we know the solution. So, for any y, the solution for y+1 can be found by adding x to the solution for y: mul x (y+1) = x + (mul x y). In Haskell we can't write (y+1) on the left hand side, so we write equivalently:
mul x y = x + (mul x (y-1))
This function will keep adding x until y is zero.
Try this also
multiply::(Num a,Eq a) => a -> a -> a
multiply a 0 = 0
multiply a b = a + multiply a (b - 1)
main = print $ multiply 5 7

Wine Tasting problem

I've spent almost all competition time(3 h) for solving this problem. In vain :( Maybe you could help me to find the solution.
A group of Facebook employees just had a very successful product launch. To celebrate, they have decided to go wine tasting. At the vineyard, they decide to play a game. One person is given some glasses of wine, each containing a different wine. Every glass of wine is labelled to indicate the kind of wine the glass contains. After tasting each of the wines, the labelled glasses are removed and the same person is given glasses containing the same wines, but unlabelled. The person then needs to determine which of the unlabelled glasses contains which wine. Sadly, nobody in the group can tell wines apart, so they just guess randomly. They will always guess a different type of wine for each glass. If they get enough right, they win the game. You must find the number of ways that the person can win, modulo 1051962371.
Input
The first line of the input is the number of test cases, N. The next N lines each contain a test case, which consists of two integers, G and C, separated by a single space. G is the total number of glasses of wine and C is the minimum number that the person must correctly identify to win.
Constraints
N = 20
1 ≤ G ≤ 100
1 ≤ C ≤ G
Output
For each test case, output a line containing a single integer, the number of ways that the person can win the game modulo 1051962371.
Example input
5
1 1
4 2
5 5
13 10
14 1
Example output
1
7
1
651
405146859
Here's the one that doesn't need the prior knowledge of Rencontres numbers. (Well, it's basically the proof a formula from the wiki but I thought I'd share it anyway.)
First find f(n): the number of permutations of n elements that don't have a fixed point. It's simple by inclusion-exclusion formula: the number of permutations that fix k given points is (n-k)!, and these k points can be chosen in C(n,k) ways. So, f(n) = n! - C(n,1)(n-1)! + C(n,2)(n-2)! - C(n,3)(n-3)! + ...
Now find the number of permutations that have exactly k fixed points. These points can be chosen in C(n,k) ways and the rest n-k points can be rearranged in f(n-k) ways. So, it's C(n,k)f(n-k).
Finally, the answer to the problem is the sum of C(g,k)f(g-k) over k = c, c+1, ..., g.
My solution involved the use of Rencontres Numbers.
A Rencontres Number D(n,k) is the number of permutations of n elements where exactly k elements are in their original places. The problem asks for at least k elemenets, so I just took the sum over k, k+1,...,n.
Here's my Python submission (after cleaning up):
from sys import stdin, stderr, setrecursionlimit as recdepth
from math import factorial as fact
recdepth(100000)
MOD=1051962371
cache=[[-1 for i in xrange(101)] for j in xrange(101)]
def ncr(n,k):
return fact(n)/fact(k)/fact(n-k)
def D(n,k):
if cache[n][k]==-1:
if k==0:
if n==0:
cache[n][k]=1
elif n==1:
cache[n][k]=0
else:
cache[n][k]= (n-1)*(D(n-1,0)+D(n-2,0))
else:
cache[n][k]=ncr(n,k)*D(n-k,0)
return cache[n][k]
return cache[n][k]
def answer(total, match):
return sum(D(total,i) for i in xrange(match,total+1))%MOD
if __name__=='__main__':
cases=int(stdin.readline())
for case in xrange(cases):
stderr.write("case %d:\n"%case)
G,C=map(int,stdin.readline().split())
print answer(G,C)
from sys import stdin, stderr, setrecursionlimit as recdepth
from math import factorial as fact
recdepth(100000)
MOD=1051962371
cache=[[-1 for i in xrange(101)] for j in xrange(101)]
def ncr(n,k):
return fact(n)/fact(k)/fact(n-k)
def D(n,k):
if cache[n][k]==-1:
if k==0:
if n==0:
cache[n][k]=1
elif n==1:
cache[n][k]=0
else:
cache[n][k]= (n-1)*(D(n-1,0)+D(n-2,0))
else:
cache[n][k]=ncr(n,k)*D(n-k,0)
return cache[n][k]
return cache[n][k]
def answer(total, match):
return sum(D(total,i) for i in xrange(match,total+1))%MOD
if __name__=='__main__':
cases=int(stdin.readline())
for case in xrange(cases):
stderr.write("case %d:\n"%case)
G,C=map(int,stdin.readline().split())
print answer(G,C)
Like everyone else, I computed the function that I now know is Rencontres Numbers, but I derived the recursive equation myself in the contest. Without loss of generality, we simply assume the correct labels of wines are 1, 2, .., g, i.e., not permuted at all.
Let's denote the function as f(g,c). Given g glasses, we look at the first glass, and we could either label it right, or label it wrong.
If we label it right, we reduce the problem to getting c-1 right out of g-1 glasses, i.e., f(g-1, c-1).
If we label it wrong, we have g-1 choices for the first glass. For the remaining g-1 glasses, we must get c glasses correct, but this subproblem is different from the f we're computing, because out of the g-1 glasses, there's already a mismatching glass. To be more precise, for the first glass, our answer is j instead of the correct label 1. Let's assume there's another function h that computes it for us.
So we have f(g,c) = f(g-1,c-1) + (g-1) * h(g-1, c).
Now to compute h(g,c), we need to consider two cases at the jth glass.
If we label it 1, we reduce the problem to f(g-1,c).
If we label it k, we have g-1 choices, and the problem is reduced to h(g-1,c).
So we have h(g,c) = f(g-1,c) + (g-1) * h(g-1,c).
Here's the complete program in Haskell, with memoization and some debugging support.
import Control.Monad
import Data.MemoTrie
--import Debug.Trace
trace = flip const
add a b = mod (a+b) 1051962371
mul a b = mod (a*b) 1051962371
main = do
(_:input) <- liftM words getContents
let map' f [] = []
map' f (a:c:xs) = f (read a) (read c) : map' f xs
mapM print $ map' ans input
ans :: Integer -> Integer -> Integer
ans g c = foldr add 0 $ map (f g) [c..g]
memoF = memo2 f
memoH = memo2 h
-- Exactly c correct in g
f :: Integer -> Integer -> Integer
f g c = trace ("f " ++ show (g,c) ++ " = " ++ show x) x
where x = if c < 0 || g < c then 0
else if g == c then 1
else add (memoF (g-1) (c-1)) (mul (g-1) (memoH (g-1) c))
-- There's one mismatching position in g positions
h :: Integer -> Integer -> Integer
h g c = trace ("h " ++ show (g,c) ++ " = " ++ show x) x
where x = if c < 0 || g < c then 0
else add (memoF (g-1) c) (mul (g-1) (memoH (g-1) c))

Godel, Escher, Bach Typographical Number Theory (TNT) puzzles and solutions

In chapter 8 of Godel, Escher, Bach by Douglas Hofstader, the reader is challenged to translate these 2 statements into TNT:
"b is a power of 2"
and
"b is a power of 10"
Are following answers correct?:
(Assuming '∃' to mean 'there exists a number'):
∃x:(x.x = b)
i.e. "there exists a number 'x' such that x multiplied x equals b"
If that is correct, then the next one is equally trivial:
∃x:(x.x.x.x.x.x.x.x.x.x = b)
I'm confused because the author indicates that they are tricky and that the second one should take hours to solve; I must have missed something obvious here, but I can't see it!
In general, I would say "b is a power of 2" is equivalent to "every divisor of b except 1 is a multiple of 2". That is:
∀x((∃y(y*x=b & ¬(x=S0))) → ∃z(SS0*z=x))
EDIT: This doesnt work for 10 (thanks for the comments). But at least it works for all primes. Sorry. I think you have to use some sort of encoding sequences after all. I suggest "Gödel's Incompleteness Theorems" by Raymond Smullyan, if you want a detailed and more general approach to this.
Or you can encode Sequences of Numbers using the Chinese Remainder Theorem, and then encode recursive definitions, such that you can define Exponentiation. In fact, that is basically how you can prove that Peano Arithmetic is turing complete.
Try this:
D(x,y)=∃a(a*x=y)
Prime(x)=¬x=1&∀yD(y,x)→y=x|y=1
a=b mod c = ∃k a=c*k+b
Then
∃y ∃k(
∀x(D(x,y)&Prime(x)→¬D(x*x,y)) &
∀x(D(x,y)&Prime(x)&∀z(Prime(z)&z<x→¬D(z,y))→(k=1 mod x)) &
∀x∀z(D(x,y)&Prime(x)&D(z,y)&Prime(z)&z<x&∀t(z<t<x→¬(Prime(t)&D(t,y)))→
∀a<x ∀c<z ((k=a mod x)&(k=c mod z)-> a=c*10))&
∀x(D(x,y)&Prime(x)&∀z(Prime(z)&z>x→¬D(z,y))→(b<x & (k=b mod x))))
should state "b is Power of 10", actually saying "there is a number y and a number k such that y is product of distinct primes, and the sequence encoded by k throug these primes begins with 1, has the property that the following element c of a is 10*a, and ends with b"
Your expressions are equivalent to the statements "b is a square number" and "b is the 10th power of a number" respectively. Converting "power of" statements into TNT is considerably trickier.
There's a solution to the "b is a power of 10" problem behind the spoiler button in skeptical scientist's post here. It depends on the chinese remainder theorem from number theory, and the existence of arbitrarily-long arithmetic sequences of primes. As Hofstadter indicated, it's not easy to come up with, even if you know the appropriate theorems.
In expressing "b is a power of 10", you actually do not need the Chinese Remainder Theorem and/nor coding of finite sequences. You can alternatively work as follows (we use the usual symbols as |, >, c-d, as shortcuts for formulas/terms with obvious meaning):
For a prime number p, let us denote EXP(p,a) some formula in TNT saying that "p is a prime and a is a power of p". We already know, how to build one. (For technical reasons, we do not consider S0 to be a power of p, so ~EXP(p,S0).)
If p is a prime, we define EXPp(c,a) ≖ 〈EXP(p,a) ∧ (c-1)|(a-1)〉. Here, the symbol | is a shortcut for "divides" which can be easily defined in TNT using one existencial quantifier and multiplication; the same holds for c-1 (a-1, resp.) which means "the d such that Sd=c" (Sd=a, resp.).
If EXP(p,c) holds (i.e. c is a power of p), the formula EXPp(c,a) says that "a is a power of c" since a ≡ 1 (mod c-1) then.
Having a property P of numbers (i.e. nonnegative integers), there is a way how to refer, in TNT, to the smallest number with this property: 〈P(a) ∧ ∀c:〈a>c → ~P(a)〉〉.
We can state the formula expressing "b is a power of 10" (for better readability, we omit the symbols 〈 and 〉, and we write 2 and 5 instead of SS0 and SSSSS0):
∃a:∃c:∃d: (EXP(2,a) ∧ EXP(5,c) ∧ EXP(5,d) ∧ d > b ∧ a⋅c=b ∧ ∀e:(e>5 ∧ e|c ∧ EXP5(e,c) → ~EXP5(e,d)) ∧ ∀e:("e is the smallest such that EXP5(c,e) ∧ EXP5(d,e)" → (d-2)|(e-a))).
Explanation: We write b = a⋅c = 2x⋅5y (x,y>0) and choose d=5z>b in such a way that z and y are coprime (e.g. z may be a prime). Then "the smallest e..." is equal to (5z)y = dy ≡ 2y (mod d-2), and (d-2)|(e-a) implies a = 2x = e mod (d-2) = 2y (we have 'd-2 > 2y' and 'd-2 > a', too), and so x = y.
Remark: This approach can be easily adapted to define "b is a power of n" for any number n with a fixed decomposition a1a2...ak, where each ai is a power of a prime pi and pi = pj → i=j.
how about:
∀x: ∀y: (SSx∙y = b → ∃z: z∙SS0 = SSx)
(in English: any factor of b that is ≥ 2 must itself be divisible by 2; literally: for all natural numbers x and y, if (2+x) * y = b then this implies that there's a natural number z such that z * 2 = (2+x). )
I'm not 100% sure that this is allowed in the syntax of TNT and propositional calculus, it's been a while since I've perused GEB.
(edit: for the b = 2n problem at least; I can see why the 10n would be more difficult as 10 is not prime. But 11n would be the same thing except replacing the one term "SS0" with "SSSSSSSSSSS0".)
Here's what I came up with:
∀c:∃d:<(c*d=b)→<(c=SO)v∃e:(d=e*SSO)>>
Which translates to:
For all numbers c, there exists a number d, such that if c times d equals b then either c is 1 or there exists a number e such that d equals e times 2.
Or
For all numbers c, there exists a number d, such that if b is a factor of c and d then either c is 1 or d is a factor of 2
Or
If the product of two numbers is b then one of them is 1 or one of them is divisible by 2
Or
All divisors of b are either 1 or are divisible by 2
Or
b is a power of 2
For the open expression meaning that b is a power of 2, I have ∀a:~∃c:(S(Sa ∙ SS0) ∙ Sc) = b
This effectively says that for all a, S(Sa ∙ SS0) is not a factor of b. But in normal terms, S(Sa ∙ SS0) is 1 + ((a + 1) * 2) or 3 + 2a. We can now reword the statement as "no odd number that is at least 3 is a factor of b". This is true if and only if b is a power of 2.
I'm still working on the b is a power of 10 problem.
I think that most of the above have only shown that b must be a multiple of 4. How about this: ∃b:∀c:<<∀e:(c∙e) = b & ~∃c':∃c'':(ssc'∙ssc'') = c> → c = 2>
I don't think the formatting is perfect, but it reads:
There exists b, such that for all c, if c is a factor of b and c is prime, then c equal 2.
Here is what I came up with for the statement "b is a power of 2"
∃b: ∀a: ~∃c: ((a * ss0) + sss0) * c = b
I think this says "There exists a number b, such that for all numbers a, there does not exist a number c such that (a * 2) + 3 (in other words, an odd number greater than 2) multiplied by c, gives you b." So, if b exists, and can't be zero, and it has no odd divisors greater than 2, then wouldn't b necessarily be 1, 2, or another power of 2?
my solution for b is a power of two is :
∀x: ∃y x.y=b ( isprime(x) => x = SS0 )
isprime() should not be hard to write.

Resources