Nbvtalkatbzaonencryptionpuzzles

289
Puzzle based Teaching of Essential mathematics and programming fundamentals for Data Encryption and Allied areas. Prof NB Venkateswarlu B.Tech(SVU), M.Tech(IIT-K), Ph.D(BITS, Pilani), PDF(U of Leeds,UK) ISTE Visiting Fellow 2010-11 AITAM, Tekkali

Transcript of Nbvtalkatbzaonencryptionpuzzles

Page 1: Nbvtalkatbzaonencryptionpuzzles

Puzzle based Teaching of Essential mathematics and programming

fundamentals for Data Encryption and Allied areas.

Prof NB VenkateswarluB.Tech(SVU), M.Tech(IIT-K), Ph.D(BITS, Pilani), PDF(U of Leeds,UK)

ISTE Visiting Fellow 2010-11AITAM, Tekkali

Page 2: Nbvtalkatbzaonencryptionpuzzles

Many Thanks to The OrganizersandWishes to Participants

Page 3: Nbvtalkatbzaonencryptionpuzzles

I guess, I am an alien. How?

Page 4: Nbvtalkatbzaonencryptionpuzzles

I am not an active researcher in this area. However, I have mentored some students for their Ph.D and also I am abreast of the developments to some extent.

Of course, I too know this is not a conference where research outcomes are shared. This is a FDP where one would like to contribute in the development of faculty including his knowledge and teaching skills. Thus, I feel I am fit here!.

Page 5: Nbvtalkatbzaonencryptionpuzzles

I came here to act like a teacher. So!!!!

What is the difference between teaching and lecturing?

Page 6: Nbvtalkatbzaonencryptionpuzzles

Literacy??Numeracy???

Page 7: Nbvtalkatbzaonencryptionpuzzles

Informatics Olympiad International Collegiate Programming

Contest

Have you heard about the following?

Page 8: Nbvtalkatbzaonencryptionpuzzles

10% of the questions are related to Number theory, especially prime numbers

7-8% of the questions are related to encryption.

In all these competitions

Page 9: Nbvtalkatbzaonencryptionpuzzles

Thus, I want to impress upon on you that it is high time to introduce the puzzle based teaching and prepare/send student batches from our country also to the above and similar compititions.

Page 10: Nbvtalkatbzaonencryptionpuzzles

Some mathematics related to number theory

Some programming puzzles involving number theory

Some more puzzles exploring encryption Some concepts related to bit wise operators Some more puzzles

What am I going to cover?

Page 11: Nbvtalkatbzaonencryptionpuzzles

విషము�ను� - విషయను�

An old tale which I read during my 3rd or 4th class.

Page 12: Nbvtalkatbzaonencryptionpuzzles

కమీకక� కక కభాకష కవకచ్చా�?

Pig Latin that is played during my school days.

Page 13: Nbvtalkatbzaonencryptionpuzzles

Mathematics which is in swing in Encryption and

allied areas

Page 14: Nbvtalkatbzaonencryptionpuzzles

He considered his work is pure and never considered as “useful”.

A Mathematicians ApologyByG.H. Hardy

Page 15: Nbvtalkatbzaonencryptionpuzzles

Now, modern cryptography is at the crossroads of mathematics and computer science.

Page 16: Nbvtalkatbzaonencryptionpuzzles

16

Prime Numbers

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, …

40 = 2·20 = 2·2·10 = 2·2·2·5

2006 = 2·1003 = 2·17·59

The largest known prime number (as of December 2005) has

9,152,052 digits. (It’s the 43rd Mersenne prime number.)

Page 17: Nbvtalkatbzaonencryptionpuzzles
Page 18: Nbvtalkatbzaonencryptionpuzzles
Page 19: Nbvtalkatbzaonencryptionpuzzles

19

Euclid (~300BC): There are infinitely many prime numbers.

“Whenever you give me a finite list p1, p2, ….., pn of n primes,

then I can give you (in principle) another prime p that is not

yet in the list.”

Page 20: Nbvtalkatbzaonencryptionpuzzles

Sriram Srinivasan

Fundamental Theorem of Arithmetic All numbers are expressible as a unique

product of primes◦ 10 = 2 * 5, 60 = 2 * 2 * 3 * 5

Proof in two parts◦ 1. All numbers are expressible as products

of primes◦ 2. There is only one such product sequence

per number

Page 21: Nbvtalkatbzaonencryptionpuzzles

Sriram Srinivasan

Fundamental Theorem proof First part of proof

◦ All numbers are products of primes

Let S = {x | x is not expressible as a product of primes}

Let c = min{S}. c cannot be prime

Let c = c1 . c2

c1, c2 < c Þ c1, c2 Ï S (because c is min{S})

\ c1, c2 are products of primes Þ c is too

\ S is an empty set

Page 22: Nbvtalkatbzaonencryptionpuzzles

Sriram Srinivasan

Fundamental Theorem proof Second part of proof

◦ The product of primes is unique

Let n = p1p2p3p4… = q1q2q3q4…

Cancel common primes. Now unique primes on both sides

Now, p1 | p1p2p3p4

Þ p1 | q1q2q3q4…

Þ p1 | one of q1, q2, q3, q4…

Þ p1 = qi which is a contradiction

Page 23: Nbvtalkatbzaonencryptionpuzzles

Prime Numbers

Some Facts about primes:

1. A number p is prime is p has only 2 divisors 1 and p.

2. Even numbers >2 are not primes.

3. An odd number p>3 is not prime if it has a divisor d: 1<d<=sqrt(n).

4. 1 is not prime;

5. Small primes: 2,3,5,7,11,13,17,19,23, etc Do you get any pattern?

How to test primality:

1. Eliminate directly the cases 1, 2, 3, multiple of 2 or 3.

2. Serch for an odd divisor of n amongst 3, 5, 7, …., sqrt(n)

3. If any the number is not prime.

Recall:

d is divisor of n iff n%d==0

Page 24: Nbvtalkatbzaonencryptionpuzzles

Prime Number Testing:

int isPrime(long p){ long d; ìnt ans;

if(p==1) return 0;if(p==2 || p==3) return 1;if(p%2==0 || p%3==0) return 0;

for(d=3;d<=sqrt(p);d=d+2)if(n%d==0) return 0;

return 1;}

Prime Numbers - Functions

Prime Number Decomposition :

int prime_decomp(long n, int p[], int pow[]){int d, nr=0, count = 0, power;for(d=2;d<=n;d++)

if(n%d==0 && isPrime(d)){ for(power=0;n

%d==0;power++) {

n=n/d; } p[count] = d; pow[count] = power; count++;

}return;}

Page 25: Nbvtalkatbzaonencryptionpuzzles

Find all primes <=n.

#include<stdio.h> #include<conio.h> #include<math.h>

int isPrime(long p);

int main (int args,char ** argc){ long n, i; // declare the variables printf("n=");scanf("%ld",&n); printf("2, ");for(i=3;i<=n;i=i+2){

if(isPrime(i)) {

printf("%ld, ", i);}

}return 1;}

Page 26: Nbvtalkatbzaonencryptionpuzzles

The Eratosthenes Algorithm.

The algorithm finds all primes less than a number n using sieving.

We strart from a list that contains all the numbers 0,1,2,3, ….,n.

Repeat removing from the list all the multiples of 2, 3, 5, etc.

Example:

Initial: List=(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18, 19, 20)

Multiples of 2: List=(0,1,2,3,0,5,0,7,0,9,0,11,0,13,0,15,0,17,0, 19, 0)

Multiples of 3: List=(0,1,2,3,0,5,0,7,0,0,0,11,0,13,0,0,0,17,0, 19, 0)

Multiples of 5 have been already removed.

The list of primes is (2,3,5,7,,11,13,17,19).

Facts:

The most efficient solution for finding all primes.

Page 27: Nbvtalkatbzaonencryptionpuzzles
Page 28: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<conio.h> #include<math.h>

int main (int args,char ** argc){ long n, i, d, primes[100000]; // declare the variables

printf("n=");scanf("%ld",&n);

for(i=0;i<=n;i++)primes[i]=i;

for(d=2;d<=sqrt(n);d++)if(primes[d]>0){ for(i=2;i*d<=n;i++) primes[i*d]=0;}

for(i=2;i<=n;i++)if(primes[i] >0) printf("%ld, ", i);

return 1;}

Page 29: Nbvtalkatbzaonencryptionpuzzles
Page 30: Nbvtalkatbzaonencryptionpuzzles

A type of quadratic sieve can also be used to generate the prime numbers by considering the parabola . Consider the points lying on the parabola with integer coordinates  for , 3, .... Now connect pairs of integer points lying on the two branches of the parabola, above and below the -axis. Then the points where these lines intersect the -axis correspond to composite numbers, while those integer points on the positive -axis which are not crossed by any lines are prime numbers.

Quadratic Sieve

Page 31: Nbvtalkatbzaonencryptionpuzzles
Page 32: Nbvtalkatbzaonencryptionpuzzles
Page 33: Nbvtalkatbzaonencryptionpuzzles
Page 34: Nbvtalkatbzaonencryptionpuzzles

An Old AIPO Competition Problem

A integer number n is valuable if has lots of prime divisors. For example: 72=2^3*3^2 has only 2 prime divisors and it is less valuable

than 30=2*3*5 that has 3 prime divisors. Given an array of integers find which number is the most valuable using

the above rule.Example: a= (2,3,4,6,9) the result is 6 with 2 primes.For a number we need its prime number decomposition.

int nr = prime_decomp(n, p, pow);nr number of prime divisorsp array with nr elements representing the prime

divisorspow array with nr elements representing the primes’

powersTHIS IS A MAXIMUM PROBLEM.

Page 35: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<conio.h> #include<math.h>

int prime_decomp(long n, int p[], int pow[]);

int main (int args,char ** argc){ long n, a[100000], max=-32000, pos=-1;int p[100], pow[100];printf("n=");scanf("%ld",&n); for(i=0;i<n;i++) {

scanf("%d",&a[i]);}for(i=0;i<n;i++){

nr = prime_decomp(n, p, pow);if( max<nr) {

max=nr;pos=i;}

}printf("Most Valuable Nr: %d", a[pos]);

return 1;}

Page 36: Nbvtalkatbzaonencryptionpuzzles

GCD (Greatest Common Divisor) gcd(a,b) = the greatest of the divisors of a,b Many ways to compute gcd

◦ Extract common prime factors Express a, b as products of primes Extract common prime factors gcd(18, 66) = gcd(2*3*3, 2*3*11) = 2*3 = 6 Factoring is hard. Not practical

◦ Euclid’s algorithm

Page 37: Nbvtalkatbzaonencryptionpuzzles

r

r1r

r = a % b

Euclid’s algorithm

a

b

b

r % r1 = 0. \ gcd (a,b) = r1

r1 = b % r

1

2

3

Page 38: Nbvtalkatbzaonencryptionpuzzles

Proof that r1 divides a and b

Euclid’s algorithm proof

r1 | rb = r1 + r

r1 | b

a = qb + rr1 | br1 | r

r1 | a

Page 39: Nbvtalkatbzaonencryptionpuzzles

Euclid’s algorithm proof (contd) Proof that r1 is the greatest divisor

Say, c | a and c | b

c | qb + r

c | r

c | q’b + r1

c | r1

Page 40: Nbvtalkatbzaonencryptionpuzzles

Linear Combination ax + by = “linear combination” of a and b

◦ 12x + 20y = {…, -12,-8,-4,0,4,8,12, … } The minimum positive linear combination of

a & b = gcd(a,b)◦ Proof in two steps: 1. If d = min(ax+by) and d > 0, then d | a, d | b 2. d is the greatest divisor.

Page 41: Nbvtalkatbzaonencryptionpuzzles

GCD & Linear combination (contd.)

Let S = {z = ax + by | z > 0 }

Let d = min{S} = ax1 + by1

Let a = qd + r. 0 <= r < d

r = a - qd = a - q(ax1 + by1)

r = a(1 - qx1) + (-qy1)b

If r > 0, r Î S

But r < d, which is a contradiction, because d = min{S}

\ r = 0 Þ d | a

Page 42: Nbvtalkatbzaonencryptionpuzzles

GCD & Linear combination (contd.)

Let c | a, c | b, c > 0

a = cm, b = cn

d = ax1 + by1 = c(mx1 + ny1)

Þ c | d

Þ d is the gcd

Second part of proof Any other divisor is smaller than d

Page 43: Nbvtalkatbzaonencryptionpuzzles

Summary 1 All numbers are expressible as unique

products of prime numbers GCD calculated using Euclid’s algorithm gcd(a,b) = 1 Þ a & b are mutually prime gcd(a,b) equals the minimum positive

ax+by linear combination

Page 44: Nbvtalkatbzaonencryptionpuzzles

Modular/Clock Arithmetic 1:00 and 13:00 hours are the same

◦ 1:00 and 25:00 hours are the same 1 º 13 (mod 12) a º b (mod n)

◦ n is the modulus ◦ a is “congruent” to b, modulo n◦ a - b is divisible by n◦ a % n = b % n

Page 45: Nbvtalkatbzaonencryptionpuzzles

Modular Arithmetic a º b (mod n), c º d (mod n) Addition

◦ a + c º b + d (mod n) Multiplication

◦ ac º bd (mod n)

a - b = jn

c - d = kn

a + c - (b + d) = (j + k) n

Page 46: Nbvtalkatbzaonencryptionpuzzles

Modular Arithmetic (contd.) Power

◦ a º b (mod n) Þ ak º bk (mod n)

Going n times around the clock ◦ a + kn º b (mod n)

Using induction,

If ak º bk (mod n),

a . ak º b . bk (mod n), by multiplication rule

\ ak+1 º bk+1 (mod n)

Page 47: Nbvtalkatbzaonencryptionpuzzles

Chinese Remainder Theorem m º a (mod p), m º a (mod q)

Þ m º a (mod pq) (p,q are primes)

m-a = cp.

Now, m-a is expressible as p1. p2 .p3 . . .

If m - a is divisible by both p and q,

p and q must be one of p1 , p2 , p3

Þ m - a is divisible by pq

Page 48: Nbvtalkatbzaonencryptionpuzzles

GCD and modulus If gcd(a,n) = 1, and a = b (mod n),

then gcd(b,n) = 1

a º b (mod n) Þ a = b + kn

gcd(a,n) = 1

ax1 + ny1 = 1, for some x1 and y1

(b + kn)x1 + ny1 = 1

bx1 + n(kx1 + y1) = bx1 + ny2 = 1

gcd(b,n) = 1

Page 49: Nbvtalkatbzaonencryptionpuzzles

Multiplicative Inverse If a, b have no common factors, there exists

ai such that a.ai º 1 (mod b)◦ ai is called the “multiplicative inverse”

gcd(a,b) = 1 = ax1+ by1, for some x1 and y1

ax1 = 1 – by1

ax1 = 1 + by2 (making y2 = -y1)

ax1 - 1 = by2

ax1 º 1 (mod b) (x1 is the multiplicative inverse)

Page 50: Nbvtalkatbzaonencryptionpuzzles

Summary 2 Modular arithmetic

◦ Addition, multiplication, power, inverse Chinese Remainder Theorem

◦ If m a (mod p) and m a (mod q),then m a (mod pq)

Relationship between gcd and modular arithmetic◦ gcd(a,b) = 1 Þ aai º 1 (mod b)

Page 51: Nbvtalkatbzaonencryptionpuzzles

Euler’s Totient function f(n) = Totient(n)

= Count of integers £ n coprime to n◦ f(10) = 4 (1, 3, 7, 9 are coprime to 10)◦ f(7) = 6 (1, 2, 3, 4, 5, 6 coprime to 10)

f(p) = p - 1, if p is a prime

Page 52: Nbvtalkatbzaonencryptionpuzzles

Totient lemma #2: product f(pq) = (p - 1)(q - 1) = f(p) . f(q)

◦ if p and q are prime

Which numbers £ pq share factors with pq?

1.p, 2.p, 3.p, … (q-1)p and

1.q, 2.q, 3.q, … (p-1)q and

pq

The rest are coprime to pq. Count them.

f(pq) = pq - (p - 1) - (q - 1) - 1 = (p - 1)(q - 1)

Page 53: Nbvtalkatbzaonencryptionpuzzles

Totient lemma #3: power f(pk) = pk - pk-1 , if p is prime and k > 0

Only numbers that are a multiple of p have a

common factor with pk :

1.p, 2.p, 3.p, … pk-1 . p and

The rest don’t share any factors, so are coprime

\ f(pk) = pk - pk-1

Page 54: Nbvtalkatbzaonencryptionpuzzles

Totient lemma #4: product f(mn) = f(m) . f(n)

◦ if m and n are coprime ( gcd(m,n) = 1)

Organize into a matrix of m columns, n rows

1 2 3 … r … m

m+1 m+2 m+3 m+r … 2m

2m+1 2m+2 2m+3 2m+r … 3m

(n-1)m+1 (n-1)m+2 (n-1)m+3 (n-1)m+r nm

Page 55: Nbvtalkatbzaonencryptionpuzzles

Totient lemma #4 (contd.)

If gcd(m,r) = 1, gcd(m,km+r) = 1

Þ All cells under that rth column have no common

factors with m

Þ Others have a common factor with mn, so can be

eliminated

Þ f(m) columns survive

Step 1: Eliminate columns

Page 56: Nbvtalkatbzaonencryptionpuzzles

Totient lemma #4 (contd.) Step 2: Examine cells in remaining columns

No two cells in a column are congruent mod n

Because if im + r º jm + r (mod n), im + r - jm - r = kn

Þ n | (i - j), which is not possible because i - j < n

Because there are n (non-congruent) cells in each

column, label them as 0, 1, 2, … n-1 in some order.

Þ f(n) cells in each column coprime to n

Þ f(n) f(m) cells left that are coprime to both m and n

Page 57: Nbvtalkatbzaonencryptionpuzzles

Totient lemma #5

If gcd(c,n) = 1 and x1,x2,x3 … xf(n) are

coprime to n, then cx1,cx2,… cxf(n) are

congruent to x1,x2,x3… in some order.

◦ 1, 3, 5, 7 are coprime to 8.

◦ Multiply each with c=15, (also coprime to 8)

◦ {15, 45, 75, 105} º {7, 5, 3, 1} (mod 8)

Page 58: Nbvtalkatbzaonencryptionpuzzles

Totient lemma #5 (contd.)

cxi is not º cxj (mod n). Because if cxi º cxj (mod n)

Þ c(xi - xj) = kn . But gcd(c,n) = 1

Þ n | (xi - xj), which is impossible because xi - xj < n

Remember the old identity:

gcd(a,n) =1 and a º b (mod n) Þ gcd(b,n) = 1

Let cxi º b (mod n)

gcd(cxi, n) = 1 Þ gcd(b,n) = 1

\ b must be one of xj

Page 59: Nbvtalkatbzaonencryptionpuzzles

Euler’s Theorem

If gcd(a,n) = 1, af(n) º 1 (mod n)

Consider x1, x2, … xf(n) < n and coprime to nSince a is also coprime to n, from previous result ax1 º xi (mod n), ax2 º xj (mod n), … etc.

Þ af(n) x1x2x3…xf(n) º x1x2x3…xf(n) (mod n)

Þ af(n) x º x (mod n) where x = x1x2x3…xf(n)

Þ n | x(af(n) - 1) But n doesn’t divide x Þ n | (af(n) - 1) Þ af(n) º 1 (mod n)

Page 60: Nbvtalkatbzaonencryptionpuzzles

Fermat’s little theorem Special case of Euler’s theorem.

◦ If gcd(a,p) = 1 and p is prime, ap-1 º 1 (mod p)

Because f(p) = p - 1

Page 61: Nbvtalkatbzaonencryptionpuzzles
Page 62: Nbvtalkatbzaonencryptionpuzzles

62

Twin primes

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, …

Are there infinitely many twin primes?

J. G. van der Corput (1939): There are infinitely many triples of primes in arithmetic progression.

Ben Green and Terence Tao (2004): There exist sequences of primes in arithmetic progression of any given length.

Page 63: Nbvtalkatbzaonencryptionpuzzles

RSA Algorithm Bob generates public and private keys

◦ public key : encrypting key e and modulus n◦ private key: decrypting key d and modulus n

Alice wants to send Bob a message m◦ m treated as a number

Alice encrypts m using Bob’s “public pen”◦ encrypted ciphertext, c = me (mod n)

Bob decrypts using his own private key◦ To decrypt, compute cd (mod n). Result is m

Page 64: Nbvtalkatbzaonencryptionpuzzles

RSA Key Generation Bob selects primes p, q computes n = pq f(n) = f(p) f(q) = (p - 1) (q - 1) Select e, such that gcd(e, f(n)) = 1 Compute the decrypting key, d, where

◦ ed º 1 (mod f(n)) Bob publishes public key info: e, n Keeps private key: d, n Important: m < n

Page 65: Nbvtalkatbzaonencryptionpuzzles

RSA Key Generation Bob selects primes p, q computes n = pq f(n) = f(p) f(q) = (p - 1) (q - 1) Select e, such that gcd(e, f(n)) = 1 Compute the decrypting key, d, where

◦ ed º 1 (mod f(n)) Bob publishes public key pair: e, n Keeps private key: d, n

p = 3, q = 11 Þ n = 33

f(n) = (3 - 1)(11 - 1) = 20 e = 7

7d = 1 (mod 20) Þ d = (1 + 20k)/7 Þ d = 3

Public key = (7, 33)Private key = (3, 33)

Page 66: Nbvtalkatbzaonencryptionpuzzles

RSA algorithm Treat each letter or block as m (m < n)

◦ n = 33, e = 7, d = 3 Encryption: for each m

compute c=me (mod n)

Decryption: for each c, compute cd (mod n)

“RSA” Þ {18, 19, 1}

63 % 33 Þ {18133 % 33 Þ {18, 19

13 % 33 Þ {18, 19, 1}

187 % 33 Þ {6197 % 33 Þ {6, 1317 % 33 Þ{6, 13, 1}

Page 67: Nbvtalkatbzaonencryptionpuzzles

RSA proof

Prove c = me (mod n) Þ cd(mod n) = m

Review:

a º b (mod n) Þ ak º bk (mod n)

a < n Þ a = a (mod n)

gcd(a,n) = 1 Þ af(n) º 1 (mod n)

a (mod p) º a (mod q) º m = a (mod pq)

f(pq) = f(p)f(q)

ed º 1 (mod f(n) ) Þ ed = 1 + k f(n)

Page 68: Nbvtalkatbzaonencryptionpuzzles

RSA proof (contd.)

c = me (mod n) Þ c º me (mod n)

cd º med (mod n)

Consider, med (mod p) and med (mod q)

If p | m, med (mod p) = 0 = m (mod p)

If not, med (mod p) º m1+k f (n) (mod p)

º m. mk f (p) f (q) (mod p)

º m. (m f (p)) k f (q) (mod p)

º m. (1) k f (q) (mod p) (by euler)

º m (mod p)

Page 69: Nbvtalkatbzaonencryptionpuzzles

RSA proof (contd.)

So, in both cases, med º m (mod p)

Similarly, med º m (mod q)

\ med º m (mod pq) (chinese remainder theorem)

º m (mod n)

\ med (mod n) = m

Page 70: Nbvtalkatbzaonencryptionpuzzles

Creating a big random prime

n = pq

f(n) = (p - 1) (q - 1)

RSA Implementation

SecureRandom r = new SecureRandom();

BigInteger p = new BigInteger(nbits, 100, r);

n = p.multiply(q);

phi = p.subtract(BigInteger.ONE) .multiply(q.subtract(BigInteger.ONE));

Page 71: Nbvtalkatbzaonencryptionpuzzles

Select e coprime to f(n)

Select d, such that ed º 1 (mod f(n))

RSA Implementation

e = new BigInteger("3");

while(phi.gcd(e).intValue() > 1)

e = e.add(new BigInteger("2"));

d = e.modInverse(phi);

Page 72: Nbvtalkatbzaonencryptionpuzzles

Encrypt/decrypt

RSA Implementation

BigInteger encrypt (BigInteger message) {

return message.modPow(e, n);

}

BigInteger decrypt (BigInteger message) {

return message.modPow(d, n);

}

Page 73: Nbvtalkatbzaonencryptionpuzzles

73

RSA in Perl

print pack"C*", split/\D+/, `echo "16iII*o\U@{$/=$z; [(pop,pop,unpack"H*",<>)]} \EsMsKsN0[lN*1lK[d2%Sa2/d0 <X+d*lMLa^*lN%0]dsXx++lMlN /dsM0<J]dsJxp"|dc`(by Adam Back)

Until 1997 – Illegal to show

this slide to non-US citizens!

Until Jan 2000: can export RSA, but only with 512 bit keysNow: can export RSA except to embargoed destinations

Page 74: Nbvtalkatbzaonencryptionpuzzles

74

Paper Excerpt (IIT-K, 2002)

Key insight based ongeneralization of Fermat’s little theorem

Page 75: Nbvtalkatbzaonencryptionpuzzles

Google Treasure hunt 2008Find the smallest number that can be expressed asthe sum of 7 consecutive prime numbers,the sum of 17 consecutive prime numbers,the sum of 41 consecutive prime numbers,the sum of 541 consecutive prime numbers,and is itself a prime number.For example, 41 is the smallest prime number that can be expressed asthe sum of 3 consecutive primes (11 + 13 + 17 = 41) andthe sum of 6 consecutive primes (2 + 3 + 5 + 7 + 11 + 13 = 41).

Page 76: Nbvtalkatbzaonencryptionpuzzles
Page 77: Nbvtalkatbzaonencryptionpuzzles

Answers: 1. There are several other ways, but:

2=5+7, 36=5+31, 52=47+5, 100=3+97, 120=7+113, 150=11+139

2. 12

1. a pair of prime numbers which adds up to each of these totals:12, 36, 52, 100, 120, 1502. Which of the numbers in question 1 cannot be solved two or more different ways?

Page 78: Nbvtalkatbzaonencryptionpuzzles

Answer: 11 and 17

What are the only numbers between 10 and 20 which are not the sum of two prime numbers?

Page 79: Nbvtalkatbzaonencryptionpuzzles

Answer: 23 and 29

Find the two primes between 15 and 30 for which, if you double them and add 1, the result is still prime. These are called “Sophie Germain primes”.

Page 80: Nbvtalkatbzaonencryptionpuzzles

Answer: Only up to x=41: [41 x 41] + 41 + 41 can

be distributed as 41 x [41+41+41] - that is, a multiple of 41

Does the equationx² + x + 41 give prime answers for all values x = 1,2,3...?

Page 81: Nbvtalkatbzaonencryptionpuzzles

Answer: 3, 5, 13, 89, 233

The “Fibonacci sequence” involves adding the last two numbers to get the next: 1, 1, 2, 3, 5, 8, 13... Find the first five Fibonacci numbers which are prime.

Page 82: Nbvtalkatbzaonencryptionpuzzles

Answer: Start with a two digit number expressed as

(10a+b)

Take any number and then subtract the reverse of its digits. eg 43-34=9. Are there are numbers less than a thousand which give a prime result?

Page 83: Nbvtalkatbzaonencryptionpuzzles

Answer: Several possible methods. Try squaring

(6n±1)

Show why all prime numbers (5 or greater) when squared are one more than a multiple of 24.

Page 84: Nbvtalkatbzaonencryptionpuzzles

Answer: 24,157,817

What is the first Fibonacci prime greater than a million?

Page 85: Nbvtalkatbzaonencryptionpuzzles

Answer: 7, 157, 307, 457, 607, 757, 907

Find the smallest list of seven primes which are all equally spaced.

Page 86: Nbvtalkatbzaonencryptionpuzzles

“Goldbach’s Conjecture” claims there are none. But no-one knows for sure. Good luck.

Be the first person ever to find an even number which is not the sum of two primes.

Page 87: Nbvtalkatbzaonencryptionpuzzles

Answer: Use some modular arithmetic, for example

38 ≡ 2 (mod12), that is the difference between 38 and 2 is a multiple of 12

Why are all Sophie Germain primes, and the primes resulting from doubling them and adding 1, one less than a multiple of six?

Page 88: Nbvtalkatbzaonencryptionpuzzles

Answer: None of them!  All permutations of 135 are

multiples of 3.

How many of the three digit numbers that can be made from all of the the digits 1, 3 and 5 (used only once each) are prime?

Page 89: Nbvtalkatbzaonencryptionpuzzles

Answer: 12343.  Two odds add up to an even, so one

of the primes must be 2.

12345 can be expressed as the sum of two primes in exactly one way. What is the larger of the two primes whose sum is 12345?

Page 90: Nbvtalkatbzaonencryptionpuzzles

Answer:  There are none.  Here's why: Assume 2p+1 is a perfect

square.  2p+1 is odd, and all odd perfect squares are equivalent to 1 (mod 4), so 2p is equivalent to 0 (mod 4), in other words it is a multiple of 4.  That means p is even, so it must be 2, the only even prime number.  But 2*2+1=5, which is not a perfect square.

Find all prime numbers p such that 2p+1 is a perfect square.

Page 91: Nbvtalkatbzaonencryptionpuzzles

Answer: p=13 is the only solution.  Here's why (solution

by Chris Braun): Assume 2p+1 is a cube. 2p = q3-1 = (q-1)(q2+q+1) Both factors of the RHS are at least 2, because

q is odd and bigger than 1.  2p is the product of two primes, so if 2p=ab, and both a and b are larger than 1, then a=2 and b=p or vice versa.  q-1 is even, and so it must be 2, so q=3, which makes q2+q+1 equal to 13.

Find all prime numbers p such that 2p+1 is a perfect cube.

Page 92: Nbvtalkatbzaonencryptionpuzzles

Prime Twin PairsOne of the first things noticeable about tables of primes is that there are many instances of pairs of prime numbers with the form n and n + 2. Examples are 11 and 13, 17 and 19, 29 and 31, 101 and 103, 881 and 883, and so on. These are sometimes called prime twin pairs. No one has ever determined if this is an interesting property of numbers or just a curious coincidence. The instances of pairs of prime numbers decrease for ever larger numbers. This leads to the question: Is there a largest prime twin pair? Like most questions about primes, this one has yet to be answered. No such simple proof as Euclid's exists for prime twin pairs.

Page 93: Nbvtalkatbzaonencryptionpuzzles

Answer: base 2: 10 base 3: 201 base 4: 103 base 5: 4302 Base 10: 987654103

What is the largest prime with distinct digits when written in base n.

Page 94: Nbvtalkatbzaonencryptionpuzzles

If a(n) is a number in base n system, then largest prime number which uses the digits only once will be using n-1 digits of base n.

def a(n) :....if n==2 : return 2....if n==3 : return 19....for P in Permutations(range(n-1, -1, -1), n-1) :........N = sum(P[-1-i]*n^i for i in range(n-1))........if is_prime(N) : return N

Page 95: Nbvtalkatbzaonencryptionpuzzles

Every integer can be represented as a string of zeroes and ones. Define P(x) to be true if the number of ones in the binary representation of x is prime and false otherwise.

Page 96: Nbvtalkatbzaonencryptionpuzzles

Prime Squares       Imagine that all of the primes are concatenated to form an infinite sequence of decimal digits        2 3 5 7 11 13 17 19 23 29 31 37 ... Within this sequence of digits there will be squares, cubes, and other numbers of interest. For example, 32=25 appears in this short portion of the sequence at 23 29. The square 16 occurs at 61 67.        Find larger squares imbedded in the sequence of concatenated primes, and spanning 2 or more primes. To be listed, you must find a larger square than the ones already found by other solvers. 

Page 97: Nbvtalkatbzaonencryptionpuzzles

Abundant Numbers        A whole number N is called abundant if the sum of its divisors is more than 2N. For example, 12 is the first abundant number. The sum of its divisors 1, 2, 3, 4, 6, 12 is 28, which is more than 2×12. The smallest abundant number that is not divisible by 2 is 945 = 33×5×7. What is the smallest abundant number which not divisible by 2 or 3? 

Page 98: Nbvtalkatbzaonencryptionpuzzles

Sum of Squares        Which whole numbers are equal to the sum of the squares of their prime divisors? For example, 16=2×2×2×2=2²+2²+2²+2² and 27=3×3×3=3²+3²+3². 

Page 99: Nbvtalkatbzaonencryptionpuzzles

Prime Order        Prove that for every N>1 the integers from 1 to N can be arranged in an order such that the sum of any two consecutive numbers is a prime. For example,9, 8, 3, 4, 1, 2, 5, 6, 7, 10

Page 100: Nbvtalkatbzaonencryptionpuzzles

Cyclic Permutations        What is the largest prime such that every cyclic permutation of its decimal digits is also prime? For example, 197, 971 and 719 are all prime. [Your prime must have at least 2 distinct digits.] 

Page 101: Nbvtalkatbzaonencryptionpuzzles

Web Counter        A certain website has a counter which records the number of hits each day, and keeps a running total. The site gets between 10 and 20 hits, inclusive, per day. The webmaster noticed that the running total was always prime. What is the largest number of days the site could be up? What is the largest number of days if the counter did not start from 1? 

Page 102: Nbvtalkatbzaonencryptionpuzzles

Powers of P (contributed by Nick McGrath)        If P and P^2+8 are both primes, prove that P^3+16 is also prime. 

Page 103: Nbvtalkatbzaonencryptionpuzzles

Sum of Two        Find 3 integers such that the sum of any 2 of them is a prime.        Find an expression that generates all solutions. 

Page 104: Nbvtalkatbzaonencryptionpuzzles

Prime Digital Sums #1        The digital sum D(n) of an integer n is the sum of its decimal digits. For example, D(123)=6. Let p(n) denote the nth prime. Show that there are no primes such that p(n) = D(n). 

Page 105: Nbvtalkatbzaonencryptionpuzzles

Prime Digital Sums #2        The digital sum D(n) of an integer n is the sum of its decimal digits. For example, D(123)=6. Let p(n) denote the nth prime. Show that there are no primes such that D(p(n)) = n. 

Page 106: Nbvtalkatbzaonencryptionpuzzles

Prime Digital Sums #3        The digital sum D(n) of an integer n is the sum of its decimal digits. For example, D(123)=6. Let p(n) denote the nth prime. Show that there are infinitely many primes such that D(p(n)) = D(n). This problem was first proposed by G. L. Honaker Jr. in 1987. 

Page 107: Nbvtalkatbzaonencryptionpuzzles

5 Factors        The first 2 consecutive whole numbers each having 2 distinct prime factors are 14=2×7 and 15=3×5. The first 2 consecutive whole numbers each having 3 distinct prime factors are 230=2×5×23 and 231=3×7×11. The first 3 consecutive whole numbers each having 2 distinct prime factors are 20=22×5, 21=3×7 and 22=2×11. The first 3 consecutive whole numbers each having 3 distinct prime factors are 644=22×7×23, 645=3×5×43 and 646=2×17×19.        Find the first 3 consecutive whole numbers each having 5 distinct prime factors. 

Page 108: Nbvtalkatbzaonencryptionpuzzles

Factors #2        Find the smallest whole number N such that N+1 has 1 prime factor, N+2 has 2 prime factors, ..., N+k has k prime factors. For distinct prime factors the solution for k=3 is N=63, since 64 has factor 2, 65 has factors 5 and 13, and 66 has factors 2, 3, and 11. For total prime factors the solution for k=3 is N=60, since 61 has factor 61, 62 has factors 2 and 31, and 63 has factors 3, 3, and 7.        Solve for k=4 through 6 for distinct prime factors, and k=4 through 7 for total prime factors. 

Page 109: Nbvtalkatbzaonencryptionpuzzles

Twice Prime        (A) Prove that a triangle with integer sides cannot have an area that is prime. (B) Find a triangle with rational sides whose area and perimeter are both prime. 

Page 110: Nbvtalkatbzaonencryptionpuzzles

Binary and Decimal        Do there exist an infinite number of binary numbers which are prime, such that when their digits are interpreted as decimal numbers they are also prime? For example 112=3 is prime and 11 is prime; 1012=5 is prime and 101 is prime; 1112=7 is prime but 111=3×37 is composite. 

Page 111: Nbvtalkatbzaonencryptionpuzzles

 Kissing Primes #1        We will say two primes kiss if both of their concatenations are also prime. For example, 3, 37 and 67 all kiss since all of the concatenations 337, 373, 367, 673, 3767 and 6737 are prime. Find 5 primes such each one kisses all of the others. 

Page 112: Nbvtalkatbzaonencryptionpuzzles

Kissing Primes #2        Find 6 primes which all kiss one another (that is, all 30 of their pairwise concatenations are also prime). 

Page 113: Nbvtalkatbzaonencryptionpuzzles

Kissing Primes #3        Find 7 primes such that the most pairs kiss (that is, as many as possible of their 42 pairwise concatenations are also prime). 

Page 114: Nbvtalkatbzaonencryptionpuzzles

3 Primes        Find 3 primes such that all of their 12 possible concatenations are also prime. For example, given the primes 3, 7 and 13, the concatenations are 37, 73, 313, 133, 713, 137, 3713, 3137, 7313, 7133, 1337 and 1373, of which 6 are prime and 6 are composite. 

Page 115: Nbvtalkatbzaonencryptionpuzzles

Up to 35       Suppose that S is a set of N distinct positive integers, and that no member of S has a prime factor greater than 35. Let P be the set of products of members of S taken 2 at a time. (For example, if x, y and z are members of S, then xy, xz and yz will be members of P.)        What is the smallest value of N for which it is certain that P contains a square? 

Page 116: Nbvtalkatbzaonencryptionpuzzles

Square and Prime        Kenny has gone to a lecture by Jenny, a famous mathematician. He tells Lenny that Jenny handed everyone at the lecture 2 cards, one containing a 5-digit prime, and the other containing a 5-digit square. All of the cards held different numbers. Then she asked everyone to add their 2 numbers, and amazingly they all got the same sum. Kenny says it's lucky that Lenny didn't attend, because then the trick would have been impossible.        What was the sum they all got? 

Page 117: Nbvtalkatbzaonencryptionpuzzles

Differences       What is the largest number of distinct positive integers you can have such that the difference between any two of them is prime, and this difference divides both of those numbers? 

Page 118: Nbvtalkatbzaonencryptionpuzzles

Differences #2        What is the largest number of distinct positive integers you can have such that most of their pairwise differences are prime? For example, among (2, 4, 6, 11, 13, 15) there are 15 pairwise differences, of which 10 are prime. 

Page 119: Nbvtalkatbzaonencryptionpuzzles

Prime Digits        Find a prime number where replacing all occurrences of one of the decimal digits it contains by any other digit produces another prime. For example, suppose we chose the digit 6 in the prime 1663. Then the 9 integers 1003, 1113, 1223, etc. would all need to be prime. 

Page 120: Nbvtalkatbzaonencryptionpuzzles

Prime Digits #2        Let D be any decimal digit. For each decimal digit D, find the largest integer such that replacing each of its distinct decimal digits by D produces a prime. For example, if D is 3 and the chosen integer were 572251, then all of the integers 572253, 573351, 372231 and 532251 would need to be prime. 

Page 121: Nbvtalkatbzaonencryptionpuzzles

Prime Density #1       Let P be a prime of D digits, and consider the substrings of the digits of P with lengths greater than 1 and less than D.  For example, if P is 1373, then the substrings are 13, 137, 37, 373 and 73.  In this case they are all prime.  Let the substring length SL(P) be the combined length of all substrings of P, and the prime substring length PSL(P) be the combined length of all substrings which are prime (with leading zeros allowed).  Then let the prime substring density PSD(P) be PSL(P)/SL(P).  So SL(1373)=PSL(1373)=12 and PSD(1373)=1.        (A) Find the largest prime P for which PSD(P) is 1. (B) Find the 10-digit prime P for which PSD(P) is greatest. 

Page 122: Nbvtalkatbzaonencryptionpuzzles

Prime Density #2        Let the prime substring density be defined as above.  Find the largest prime P for which PSD(P) > 1/2, or show that there are an infinite number of such primes. 

Page 123: Nbvtalkatbzaonencryptionpuzzles

Prime Density #3        Let N be an integer of D digits, and consider all substrings of the digits of N with lengths from 1 to D, inclusive, but disallowing strings with leading zeroes.  For example, if N is 10305, then the substrings are 1, 10, 103, 1030, 10305, 3, 30, 305, and 5.  Let the substring length SL(N) be the combined length of all such substrings of N, and the prime substring length PSL(N) be the combined length of all such substrings which are prime.  Then let the prime substring density PSD(N) be PSL(N)/SL(N).  So SL(10305)=22, PSL(10305)=5 and PSD(10305)=5/22, or about 0.227.        Using this new definition, (A) find the largest integer whose prime substring density is 1, and (B) find the 10-digit integer whose prime substring density is greatest. 

Page 124: Nbvtalkatbzaonencryptionpuzzles

Twin Prime Magic Square        Twin primes are primes whose difference is 2, such as 5 and 7. Using only the smaller numbers in sets of twin primes, form a 3x3 Magic Square (a 3x3 array of numbers where all of the rows and columns, and both of the main diagonals have the same sum). Find the Magic Square whose sum is smallest using only 9-digit twin primes. 

Page 125: Nbvtalkatbzaonencryptionpuzzles

Between 2 and 3        It is well known that there are an infinite number of primitive integer solutions to A2+B2=C2 and that there are no non-trivial integer solutions to A3+B3=C3. Where is the boundary between the solvable and the unsolvable?        It does not make much sense to talk about integer equations Ar+Br=Cr where r is an arbitrary real number, so we approach the problem in a more abstract way. The radical of an integer N, denotedrad(N), is defined as the product of the distinct prime factors of N. Thus, for example, rad(6)=rad(12)=rad(18)=rad(36)=6. Define the power of N, denoted power(N), as log(N)/log(rad(n)). For example, power(32)=5.        Define the power of a triple A+B=C, denoted power(A,B,C), where gcd(A,B,C)=1 to be min(power(A),power(B),power(C)). Here are two examples:power (61^4, 3^13*53, 2^13*5*7^4) = 3.6008power (5^9*23, 2^6*3^5*17^3, 7^2*19^5) = 3.7135       Find one or more triples of higher power. [Extra credit: Find a triple of power 4 or greater.] [Extra-extra credit: Determine the upper limit, or prove that none exists.] 

Page 126: Nbvtalkatbzaonencryptionpuzzles

 Rubin Prime Conjecture        Prove that for every integer n>1 there is at least one prime between n and n+(ln n)².

Page 127: Nbvtalkatbzaonencryptionpuzzles

Answer: n is divisible by 6, so n2 is divisible by 36 and (n2+16) is divisible

by 4, so n2(n2+16) is divisible by 144.  Then 5 is the only additional factor we need to find in order to show the result.

If n=1 (mod 5) then n-1 isn't prime, and if n=-1 (mod 5) then n+1 isn't prime, so n must be 0, 2, or 3 (mod 5), so we'll consider those three cases:

case n=0 (mod 5): n2 is divisible by 5, and the result follows. case n=2 (mod 5): n2+16 is 22+1=0 (mod 5), and the result follows. case n=3 (mod 5): n2+16 is 32+1=0 (mod 5), and the result follows. 

Let n be an integer greater than 6. Prove that if n-1 and n+1 are both prime, then n²(n²+16) is divisible by 720.

Page 128: Nbvtalkatbzaonencryptionpuzzles

Answer: No, the converse is not true, because n2(n2+16) is divisible by 720

whenever n is a multiple of 6 and n≡0, 2, or 3 (mod 5).To find a counterexample, n-1 or n+1 must be the product of prime factors larger than 5, so n=48 is the smallest counterexample.If n=48, then n2(n2+16) is divisible by 720, but n+1=49 is not prime.

Is the converse true?  That is, if n2(n2+16) is divisible by 720, then are n-1 and n+1 both prime?

Page 129: Nbvtalkatbzaonencryptionpuzzles

Answer: Let's look at some smaller examples of numbers consisting of a

composite number of ones.  111111 has 6 1's, so it is the product of 010101 and 11.  111111111111111 has 15 1's, so it is the product of 001001001001001 and 111.

119 = 7 * 17, so it's the product of 00000010000001...0000001 and 1111111.

In general, if k is a factor of n, then (xk-1+xk-2+...+1) is a factor of (xn-1+xn-2+...+1).  Application of this general principle comes with x=10, k=7, and n=119.

Let a be the integer whose base 10 representation consists of 119 ones. Prove that a is not prime.

Page 130: Nbvtalkatbzaonencryptionpuzzles

Answer: If n is even, then n4+4n is even, so consider the case in

which n is odd. Let n=2k+1, so now we need to show that n4+42k+1 is

composite for any k > 0. n4+42k+1 = (n2+22k+1-2k+1n)(n2+22k+1+2k+1n) This clever factorization uses the trick that: a4+4b4  =  (a2+2b2-2ab)(a2+2b2+2ab) and since n4+42k+1 = n4+(4)(24k), we can let a=n and

b=2k to achieve the desired result.

 Prove composite: n4+4n, n>1.

Page 131: Nbvtalkatbzaonencryptionpuzzles

Answer: The answer is {13}.  Here's a solution: Let r,s be two consecutive values of

n, and r²+3, s�+3 are both divisible by p.  So −3=r2 (mod p),

−3=s2 (mod p), ands=r+1 (mod p)

Since r and s are two different square roots of −3 (mod p), we also have s+r=0 (mod p) These conditions are sufficient to conclude it must be the case that r=(p−1)/2 (mod p), and

s=(p+1)/2 (mod p). So then we have the product of the two square roots of −3 is 3, i.e., (p−1)(p+1)/4 = 3 (mod p)

p2−1 = 12 (mod p), which is legal since 4 and p are coprime,p2 = 13 (mod p)0 = 13 (mod p)

So 13 is the only prime that answers this question, and in fact 62+3=39 and 72+3=52 are both divisible by 13.

Find the set of all positive primes that are a factor of two consecutive terms of n²+3

Page 132: Nbvtalkatbzaonencryptionpuzzles

Find palindrome prime obtained adding the first k primes, that is to say:What is the first k, such that:Nk = 2 + 3 + 5 + 7 + 11 +…..+ pk = Prime Palindrome?Some examples for k=3324456535654403 + 324456535654423 + 324456535654553 =973369606963379326151616151597 + 326151616151623 + 326151616151659 =978454848454879332526262625197 + 332526262625233 + 332526262625369 =99757878787579911708180908180709 + 11708180908180711 + 11708180908180733 =3512454272454215312829181718192793 + 12829181718192821 + 12829181718192869 =3848754515457848312907072927070909 + 12907072927070921 + 12907072927070953 =3872121878121278312918271817281913 + 12918271817281921 + 12918271817281949 =3875481545184578332928090809082919 + 32928090809082923 + 32928090809082947 =98784272427248789

Page 133: Nbvtalkatbzaonencryptionpuzzles

A 73-digit solution with middle palindromic prime:p = 1070707070707070707070707071829182829282819281707070707070707070707070701The solution equation is (p-52) + (p) + (p+72) = (3p+20)= 3212121212121212121212121215487548487848457845121212121212121212121212123

Page 134: Nbvtalkatbzaonencryptionpuzzles

A 303-digit solution:p = 10^302 + 10*(7*10^301-70)/99 + 10^140*22001012200100221010022 + 1 Let w be "0" followed by 69 concatenations of "70". Then p is the concatenation 1w92708082907170928080729w1 Solution equation: (p-138) + (p) + (p+158) = (3p+20) These 4 primes were proved with Marcel Martin's Primo.

Page 135: Nbvtalkatbzaonencryptionpuzzles

Left or Right Truncable primesSee the following numbers which are primes and are formed by cutting by the right most digit). 73939133  7393913  739391  73939  7393  739  73  7 Also see the following numbers which are primes and are formed b cutting by the left most digit. 933739397  33739397  3739397  739397  39397  9397  397  97  7 Write a program which takes an integer and display yes if it shows either of the above characteristic; otherwise print No.

Page 136: Nbvtalkatbzaonencryptionpuzzles

J. K. Andersen has come (January, 2006) with a generalization of this puzzle:Let p184 = 331767603936186381337518604730526923225433443498541534\63216572933478421841663169727125215075424020614778993394696035966\34858212099979878129094817736602146359724182316273512181213141511

at a time from the left end of p184 gives a sequence of 92 primes.Removing 2 digits Let p1140 =686957720511887558525174658414510840176432151923825981304948\378237135960629558400414747213755738286767792781351488750517\264488672424143774793266286770364857174294438649140883405465\111650184405422520731603936126112798650690193956270492667782\252202425468175747633902739432648860601275832729600906840482\517851207730351684240852483171368592354596760617184207344771\303768615441256104709615257106329207958857891370636668654226\668627598741990159293937377616627380523797310848321354613345\824936640519215403201542663630168337125631393644321198900751\309897458118224375862155562138132204372567203408924412447426\191762625165468828155675928128109122396184327504132254486363\462573142336434187126453194249586173168628353985230306916320\165307176186115255273138159294501491217530102244194102187144\270207207114774123518132546106144140201166182339319824304125\676185525801369789378639298750449400209313132470714271252396\201303215168177114238260253260193102638141177189196377117229\113172542190366267119229110112420351285173283143252142138105\125265215598270147245157170100165362100128133129158132132180\111172135104111124168102122154101132100107102106105101102101

Page 137: Nbvtalkatbzaonencryptionpuzzles

Where are you?http://www.primepuzzles.net/puzzles/

Page 138: Nbvtalkatbzaonencryptionpuzzles

7 13 103 1009 10009 100003 1000003 10000121 100000039 1000000009 10000000033 100000000003 1000000000039 10000000000411 100000000000067

k=16 to 19 1000000000000487 

10000000000000481 100000000000000003 1000000000000000003

k=50: 10000000000000000000000000000000000000000000000009

Happy PrimesIf you iterate the process of summing the square of the decimal digits of a number, then it’s easy to see that you either reach the cycle 4->16-> 37-> 58-> 89-> 145-> 42-> 20-> 4 or arrive at 1. In the latter case you started from a "happy number". Find the least "happy prime" of k digits, for 1 <= k <= 10

Page 139: Nbvtalkatbzaonencryptionpuzzles

Composite numbers equal to the sum of primes from the least prime factor to the largest prime factor

39 = 3 x 13 = 3 + 5 + 7 + 11 + 13 Some other examples are: 10, 39, 155 & 371 

Prime Curios

Page 140: Nbvtalkatbzaonencryptionpuzzles

Assume we have written a code in which each of the digits 0 through 9 represents some other digit.

Let N be the number of perfect square integers below 10^x, which when decoded , result in primes.

Example: Code: 0123456789 -> 2548719603 Perfect Squares below 1000 that the above Code turn them prime

numbers when decoded: Before decoding {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 169, 256, 625, 729,

784} After decoding {2, 5, 7, 3,  59, 41, 89, 73,  97, 02, 593, 419, 941, 643,

607} then for this code N=15

What is the code if :

1) N is to be maximum? 2) N is to be minimum? 

Solve 1 & 2 for x = 3 , 4 & 5

Secret Code

Page 141: Nbvtalkatbzaonencryptionpuzzles

Digital Signature

med (mod n) = mde (mod n) Bob encrypts his name using private key Alice, the recipient, decrypts it using Bob’s

public key

Page 142: Nbvtalkatbzaonencryptionpuzzles

RSA Deployment If msg m > n, m chop it up in blocks < n p and q are usually 512 bits, e = 65537. Ensure p - 1 doesn’t have small prime

factors. Ensure d is large Pad m with random bits Never reuse n Sign documents very carefully

Page 143: Nbvtalkatbzaonencryptionpuzzles

Examples of RSA Attacks Exploiting algorithm parameter values

◦ Low e or d values Exploiting implementation

◦ Measuring time and power consumption of smart cards

◦ Exploiting random errors in hardware

◦ Exploiting error messages Social Engineering: Blinding attack

Page 144: Nbvtalkatbzaonencryptionpuzzles

Ellis / Diffie-Hellman Key Exchange RSA is slow in practice

◦ Encrypt AES’s keys using RSA Alice and Bob agree publicly on a prime p,

and some integer, c < p. gcd(p,c) = 1 Alice chooses a privately, and Bob chooses

b. a, b < p

Page 145: Nbvtalkatbzaonencryptionpuzzles

Ellis / Diffie-Hellman Key Exchange (contd)

Alice computes A=ca (mod p). Bob

computes B=cb (mod p) They exchange these numbers. Alice computes Ba. Bob computes Ab

Both of them compute cab (mod p) Both use this number as a key for AES.

Page 146: Nbvtalkatbzaonencryptionpuzzles

146

EXAMPLE 3

Pythagorean triples: ? x² + y² = z² ?

3² + 4² = 5²

5² + 12² = 13²

20² + 21² = 29²

? x³ + y³ = z³ ?

6³ + 8³ = 9³ -1

Page 147: Nbvtalkatbzaonencryptionpuzzles

147

Fermat’s Last “Theorem” (1637): For n = 3, 4, 5,…, there are no integer solutions to the Pythagorean equation.

Confirmed for the first time by Andrew Wiles in 1994 (=1637 + 357) !

CONCLUSIONS 3:

-Mathematics is as much about good problems as it is about good solutions.

-Very good problems may take a long time to be solved, if ever.

-Easy looking mathematical problems may need a huge “abstract machinery” to be settled.

Page 148: Nbvtalkatbzaonencryptionpuzzles

Fibonacci numbers

› Fibonacci numbers are defined as - fib(0) = 0, fib(1) = 1 - fib(n) = fib(n-1) + fib(n-2) › Example: 1, 1, 2, 3, 5, 8, 13, 21, 34… › Fibonacci numbers grow very fast › Some problems involving Fibonacci

number requires the use of BigInteger 6

Page 149: Nbvtalkatbzaonencryptionpuzzles

› Given a positive integer n, such a sum can be found using a Greedy

technique: - Take the largest Fibonacci number f lower than n - Reiterate with n-f instead of n until n-f = 0

Zeckendorf’s Theorem: every positive integer can be written in a unique way as a sum of one or more Fibonacci numbers so that the sum does not include two consecutive Fibonacci numbers.

Fibonacci numbers

Page 150: Nbvtalkatbzaonencryptionpuzzles

O(1) approximation of the nth Fibonacci number

› Binet’s formula - (p^n – (-p)^-n)/sqrt(5) - with p, the golden ratio: p = ((1+\sqrt(5)) / 2)

⋍ 1.618 › Approximation - Take the closest integer to (pn – (-p)-n)/sqrt(5) - Does not work well for large values of n 8

Fibonacci numbers

Page 151: Nbvtalkatbzaonencryptionpuzzles

Pisano period. The last one/last two/last three/last four digits of a

Fibonacci number repeats with a period of 60/300/1500/15000,

resp.

Fibonacci numbers

Page 152: Nbvtalkatbzaonencryptionpuzzles

Puzzles That can raise interest of the students.

Page 153: Nbvtalkatbzaonencryptionpuzzles

Typesetting "errors" in which exponents or multiplication signs are omitted but the resulting expression is equivalent to the original one. Examples include

Write a program which takes a wrongly printed number and displays equivalent number with caps at their correct place. Assume given input number will not be having more than 6 digits and at most two numbers raised to some power value between 1-9.

Sample Input: 2592 34425 312325 Sample Output: 2^59^2 3^4425 31^2325

Identify Printing errors

Page 154: Nbvtalkatbzaonencryptionpuzzles
Page 155: Nbvtalkatbzaonencryptionpuzzles
Page 156: Nbvtalkatbzaonencryptionpuzzles

 An integer number n is valuable if has lots of prime divisors. For

example: 72=2^3*3^2 has only 2 prime divisors and it is less valuable than 30=2*3*5 that has 3 prime divisors.

 Input: First an integer N indicating how many numbers. Second line

contains numbers out of which we need to find valuable number. Output: An integer which is valuable number. If more than one number

is valuable, smallest one can be printed. 

Example Input:272 30Sample Output:30

Finding Valuable Number (Old AIPO problem)

Page 157: Nbvtalkatbzaonencryptionpuzzles

Solution: Here, we need to decompose a number into its prime factors. For this a function prime_decomp is written whichreturns number of prime divisors of n.

 int prime_decomp(n, p, pow1);

n: the number whose prime divisors has to be found.p : array with nr elements representing the prime divisorspow1: array with nr elements representing the primes’

powersAlso, we have written a function isPrime to check whether a given

integer n is prime or not. If n is prime it returns 1 else it returns 0. As we want smallest valuable number, we will sort the given numbers

first. Then, we will find number of prime factors for each number with the help of prime_decomp method. Then, we will find the number having more prime factors.

Page 158: Nbvtalkatbzaonencryptionpuzzles

int isPrime(long p){ long d; int ans; if(p==1) return 0; if(p==2 || p==3) return 1; if(p%2==0 || p%3==0) return 0;   for(d=3;d<=sqrt(p);d=d+2) if(p%d==0) return 0; return 1; } int prime_decomp(long n, int p[], int pow1[]){ int d, nr=0, count = 0, power;

for(d=2;d<=n;d++) if(n%d==0 && isPrime(d)){ for(power=0;n%d==0;power++){ n=n/d; } p[count] = d; pow1[count] = power; count++; } return count; }

Page 159: Nbvtalkatbzaonencryptionpuzzles

int main (){ long n, a[100000], max=-32768, pos=-1,i,nr,t,j; int p[100], pow1[100];   scanf("%ld",&n);   for(i=0;i<n;i++) scanf("%d",&a[i]);   /*sorting*/ for(i=0;i<n-1;i++) for(j=0;j<n-1-i;j++)if(a[j]>a[j+1]){ t=a[j]; a[j]=a[j+1]; a[j+1]=t; } for(i=0;i<n;i++){ nr = prime_decomp(a[i], p, pow1); if( max<nr) { max=nr;pos=i; } } printf("Most Valuable Number: %d", a[pos]); return 0; }

Page 160: Nbvtalkatbzaonencryptionpuzzles

Palindromic Primes are prime numbers that read the same left to right (forwards) as from the right to left (backwards).

  Here are a few random examples: 3, 131, 71317, and 134757431   Write a program that outputs the number of palindromic primes

between two given integers, a and b. You can assume that:   1 < a,b < 106  

Sample input: 2 100  Sample output: 2 3 5 7 11

Palindromic Prime (2013 AIPO 1st Round Entry Problems)

Page 161: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<math.h> int rev(int n){ int s=0; while(n){ s=s*10+n%10; n=n/10; } return s; } int isPalin(int n){ return (n==rev(n)); } int isPrime(long p){ long d; int ans;

if(p==1) return 0; if(p==2 || p==3) return 1; if(p%2==0 || p%3==0) return 0;   for(d=3;d<=sqrt(p);d=d+2) if(p%d==0) return 0; return 1; } int main (){ int n,m, i; scanf("%d%d",&n,&m); for(i=n;i<=m;i++) if(isPrime(i)&&isPalin(i)) printf("%d\n",i); return 0; }

Page 162: Nbvtalkatbzaonencryptionpuzzles
Page 163: Nbvtalkatbzaonencryptionpuzzles
Page 164: Nbvtalkatbzaonencryptionpuzzles

int isFermat(int x, int y, int z){ return ( ((x*x)+(y*y)) ==(z*z)); } void compute(int N){ unsigned char x[10240]; int l=0,p=0,r=0; int i,j,k; for(i=0;i<10240;i++)x[i]=0; for(i=1;i<=N;i++){ for(j=1;j<=N;j++){ for(k=1;k<=N;k++){ if( (i<j&&j<k) &&isPrime3(i,j,k)&&isFermat(i,j,k)){ //printf("%d %d %d\n",i,j,k); r++; x[i]=1; x[j]=1; x[k]=1; l+=3; } else if( (i<j&&j<k) &&isFermat(i,j,k)){ x[i]=1; x[j]=1; x[k]=1; l+=3; } } } }  

Page 165: Nbvtalkatbzaonencryptionpuzzles

  for(i=1,p=0;i<10240;i++)p+=x[i]; printf("%d %d\n",r,N-p); } int main() { int i,j,l,r,h; char x[20],y[20]; FILE *IP, *OP;   printf("Enter input and output filenames\n"); scanf("%s%s",x,y); IP=fopen(x,"r"); OP=fopen(y,"w"); while(!feof(IP)){ fscanf(IP,"%d",&l); compute(l); } fclose(IP); fclose(OP); return 0; }

Page 166: Nbvtalkatbzaonencryptionpuzzles

A substring of an integer is formed from a subsequence of consecutive digits of the original integer. For example, the number 2478 contains the substrings 2478, 247, 478, 24, 47, 78, 2, 4, 7 and 8. You must find the largest integer substring which is also a prime.

InputThe input will be an integer N, (0 <= N <= 1000000000). OutputThe output will be the largest prime substring of N. If none of the substrings are

prime, then output “No Primes”

Example 12319 Output 131 Example 22486 Output 2No Primes

Prime substrings(2011 Programming Problems)

Page 167: Nbvtalkatbzaonencryptionpuzzles

Solution: We have written a function isPrime() which takes an integer and returns 1 if it is prime else returns 0. Also, we have written a function GetSub() which takes two integers start, len. A global character array number contains an integer in string fashion. The GetSub() function takes characters of this global string from start to len number of characters (digits) and converts them into an integers and returns the same. In the main, a string is read from standard input and all possible sub strings are generated and each one is verified for its primness’ then find largest of such sub-strings.

Page 168: Nbvtalkatbzaonencryptionpuzzles

long GetSub(int start, int len){ long sub = 0; int end = len + start;   for(int i = start; i < end; i++) sub = sub * 10 + number[i]; return sub; }   int main(){ long sub, BestPrime=0; scanf("%s",number); int NumDigits = strlen(number);   // UnASCII number for (int i = 0; i < NumDigits; i++) number[i] -= '0';   // Work down through all lengths (all possible subsequence lengths) for (int len = NumDigits; len > 0; len--){ for (int start = 0; start <= NumDigits - len; start++){ sub = GetSub(start, len); if (isPrime(sub) &&(sub > BestPrime)) BestPrime = sub; } } if (BestPrime > 0) printf("%ld\n",BestPrime); else printf("No Primes\n"); return 0; }

Page 169: Nbvtalkatbzaonencryptionpuzzles

One day while you were experimenting with your Ham radio when you came across a strange

message. It was comprised completely of numbers. After you studied some of the code you

noticed a pattern and eventually discovered a solution. Every lower case letter is represented by every other prime number starting with 2 and every other upper case letter is represented by every other prime number starting with 3. Also, any number that is not a prime represents a

space. For example 2 = “a”, 3 = “A”, 5 = “b”, 7 = “B”, 11 = “c”, 13 = “C”, and 4,6,8 = “ “.

 Create a program that will decode messages sent in this

prime encoding.

Prime Hamming Code

Page 170: Nbvtalkatbzaonencryptionpuzzles

Input: The first line of input will be a single integer, n, that will tell you the number of encoded messages you are to decode. Each of the next n line will contain a single message. The lines will be comprised of a list of positive integers separated from each other by a single space. The last integer on the line will be followed by an end-of-line character.

  Output: Output should be the decoded messages, one per line.   Sample Input: 61 4 89 109 191 23 133 101 2 167 47 3 101 19 88 59 157 49 5 23 167 167 23 149 39 167 47 2 103 100 61

103 167 23 83   Sample Output: I Love Math AMD is better than Intel

Page 171: Nbvtalkatbzaonencryptionpuzzles

Solution: We have a function which takes an integer and returns 1 if it is prime number otherwise returns 0. Using this function, we compute first 52 elements starting from 2 and store in a global array Allprimes. Also, we have a function which takes a prime number and returns it is location in the array Allprimes.

  We read the encrypted message into a string variable. Each

time one string is extracted using strtok() function and converted the same into an integer. If that integer is a prime number then its index in the Allprimes array is found. If it is even lower case alphabet is printed otherwise upper case is printed. If the integer is not a prime then a simple space or empty space is printed. After processing one line of encrypted message, one new line also printed.

Page 172: Nbvtalkatbzaonencryptionpuzzles

int Allprimes[52]; /* A global array to have first 52 primes*/ int index(int n){ int i; for(i=0;i<52;i++)if(Allprimes[i]==n)return i; } int main(){ int i,j,k,l,m,b; char input[1024],result[1024]="",res[128],*t,s[64]; /*computing 52 prime numbers*/ for(k=0,i=2;k<52;i++)if(isPrime(i))Allprimes[k++]=i; scanf("%d",&m);fgetc(stdin); while(m--){ scanf("%[^\n]",input);fgetc(stdin); t=strtok(input, " "); while(t!=NULL){ strcpy(s,t); b=atoi(s); if(isPrime(b)){ b=index(b); if(b%2)printf("%c", 'A'+b/2); else printf("%c",'a'+b/2); } else printf(" "); t=strtok(NULL," "); } printf("\n"); } return 0; }

Page 173: Nbvtalkatbzaonencryptionpuzzles

Consider those 5 digit numbers (i.e., between 10,000 and 99,999 inclusive) that can be written in the form

anbm

where a and b are distinct prime numbers, and n, and m are non-negative integers. How many times does the digit k appear?

 For example, there are three 5-digit numbers whose only prime factors are

13 and 19: 41743, 61009, and 89167. The digit zero appears twice, the digit one appears 3 times, and so on. There will be 10 inputs, each consisting of three positive integers, a, b, and k, in that order.

 Solution: We have written a function NTimes() which takes two integers

n and x as arguments and returns how many times x is seen in the number n as n’s digit. Also, we have written a function isPrime() which takes an integer and returns 1 if it is prime else returns 0. Also, we have written a function prime_decomp() to check whether two given prime numbers a and b are the only factors to a given number n or not. If true, it returns 1 else it returns 0. These three functions used in our main.

How many time a digit k appears?

Page 174: Nbvtalkatbzaonencryptionpuzzles

int NTimes(int n,int x){ int p=0; while(n){ if(n%10==x)p++; n=n/10; } return p; } int isPrime(int p){ int ans,d;

if(p==1) return 0; if(p==2 || p==3) return 1; if(p%2==0 || p%3==0) return 0;   for(d=3;d<p;d=d+1) if(p%d==0) return 0; return 1; } int prime_decomp(int n, int p[], int a, int b){ int d,count = 0;

for(d=2;d<n;d++) if(n%d==0 && isPrime(d)) p[count++] = d;

if(count>2)return 0; else if(count<2)return 0; if( (p[0]==a&&p[1]==b) || ( p[1]==a&& p[0]==b) ) return 1; else return 0; }

Page 175: Nbvtalkatbzaonencryptionpuzzles

int main(){ int

i,result=0,a,b,k,pp[5],n=10,x[10],y[10],z[10],j; for(i=0;i<n;i++) scanf("%d%d%d",&x[i],&y[i],&y[i]); for(j=0;j<n;j++){ a=x[j]; b=y[j]; k=z[j]; result=0; for(i=10000;i<=99999;i++){ if(i%a==0&&i%b==0) {

if(prime_decomp(i,pp,a,b))result+=NTimes(i,k); } } printf("%d\n",result); } return 0; }

Page 176: Nbvtalkatbzaonencryptionpuzzles
Page 177: Nbvtalkatbzaonencryptionpuzzles

Goldbach (1690 – 1764) The Goldbach Conjecture asserts that every even integer greater than 2 can be written as the sum of two primes.

Get a number from the user, if it is not even ask again, and then find two prime numbers that sum to the number.   INPUT/OUPUT: Enter a number? 80 80 = 7 + 73   INPUT/OUPUT: Enter a number? 5 Enter a number? 6 6 = 1 + 5  Goldbach's conjecture states that any even number larger than 2 can be expressed as the sum of two primes. But

what about the reverse: can a prime number be expressed as the sum of two even numbers? Given two positive even integers, where the second is larger than the first, compute and print the number of prime

numbers in that inclusive interval that can be expressed as the sum of two even numbers. The data file will have two numbers per line; print one line of output for each line of input.

 Test data:74 8822 1906 Output from test data:00

Hcabdlog

Page 178: Nbvtalkatbzaonencryptionpuzzles

Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence

1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...shows the first 11 ugly numbers. By convention, 1 is

included.Write a program to find and print the 1500'th ugly

number.Input and OutputThere is no input to this program. Output should consist

of a single line as shown below, with <number> replaced by the number computed.

Sample outputThe 1500'th ugly number is <number>.

Ugly Number

Page 179: Nbvtalkatbzaonencryptionpuzzles

The factorial of a number N (written N!) is defined as the product of all the integers from 1 to N. It is often defined recursively as follows:

Factorials grow very rapidly--5! = 120, 10! = 3,628,800. One way of specifying such large numbers is by specifying the number of times each prime number occurs in it, thus 825 could be specified as (0 1 2 0 1) meaning no twos, 1 three, 2 fives, no sevens and 1 eleven.

Write a program that will read in a number N (  ) and write out its factorial in terms of the numbers of the primes it contains.

InputInput will consist of a series of lines, each line containing a single integer N. The file will be

terminated by a line consisting of a single 0.OutputOutput will consist of a series of blocks of lines, one block for each line of the input. Each block

will start with the number N, right justified in a field of width 3, and the characters `!', space, and `='. This will be followed by a list of the number of times each prime number occurs in N!.

These should be right justified in fields of width 3 and each line (except the last of a block, which may be shorter) should contain fifteen numbers. Any lines after the first should be indented. Follow the layout of the example shown below exactly.

Sample input5530Sample output 5! = 3 1 1 53! = 49 23 12 8 4 4 3 2 2 1 1 1 1 1 1 1

Factors and Factorials

Page 180: Nbvtalkatbzaonencryptionpuzzles

Prime Ring Problem

Page 181: Nbvtalkatbzaonencryptionpuzzles

You are to write a program that completes above process. Sample Input 6 8 Output for the Sample Input Case 1: 1 4 3 2 5 6 1 6 5 2 3 4   Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2

Prime Ring Problem (Cont)

Page 182: Nbvtalkatbzaonencryptionpuzzles
Page 183: Nbvtalkatbzaonencryptionpuzzles
Page 184: Nbvtalkatbzaonencryptionpuzzles

It turns out that 2012 can be expressed as the sum of two primes in 27 different ways. This isn't particularly unusual, because according to the still unproven Goldbach conjecture, every even number can be written as the sum of two primes. (Odd numbers can only be written as the sum of two primes if one of the primes can be 2.) It's mildly interesting that 27 seems to be relatively low among nearby even numbers, although I haven't collected much data. It would be easier to collect it, if you were to write a program whose job it is to produce just that statistic: how many different pairs of primes sum to a given number. Fourteen is the first even number with two different pairs, (3,11) and (7,7). Eighteen has three pairs, (1,17), (5,13), and (7,11). [1 is sometimes not counted as a prime number, but we need it to make the conjecture true for 2. Zero is not prime, of course – it has an infinite number of factors.] If you happen to come up with an even number which cannot be expressed as the sum of two primes, the judges would be interested in co-authoring a paper with you.

Sample input:20102012201120000012Output for Sample input:8427

054296

PrimePairs

Page 185: Nbvtalkatbzaonencryptionpuzzles

Prime Number When we consider two integers, n and m, we say that m divides n , when

there is another integer k such that n = mk In this case, we say that n is a multiple of m and m is a divisor of n . We say that a number p is prime if and only if p is different from 1 and -1 and

the only divisors of p are 1, -1, p-p. Write a program that, for any positive integer n, a list of all prime positive

integers less than or equal to n.   Co-primes Two integers are said coprime if and only if the gcd between them is 1. For

example: mcd (17.91) = 1 then 17 and 91 are relatively prime. Find, pencil in hand, what is the biggest pair of coprime positive integers that

can be considered in the language and the computer you use. Write a program that, given an integer n, find an nxn matrix such that: aij = 1 if i and j are coprime aij = 0 if i and j are coprime

Co-primes

Page 186: Nbvtalkatbzaonencryptionpuzzles

A positive integer is called B-smooth if none of its prime factors is greater than B. For example, 1,620 has prime factorization 22 × 34 × 5; therefore 1,620 is 5-smooth because none of its prime factors are greater than 5. This definition includes numbers that lack some of the smaller prime factors; for example, both 10 and 12 are 5-smooth, despite the fact that they miss out prime factors 3 and 5 respectively. 5-smooth numbers are also called regular numbers or Hamming numbers; 7-smooth numbers are also called humble (From Wikipedia)

B-Smooth Numbers

Page 187: Nbvtalkatbzaonencryptionpuzzles

Write a program which reads a positive integer and finds whether it is B-smooth number or not, if so print B value.

Page 188: Nbvtalkatbzaonencryptionpuzzles

A k-rough number, as defined by Finch in 2001 and 2003, is a positive integer whose prime factors are all greater than or equal to k. k-roughness has alternately been defined as requiring all prime factors to strictly exceed k.

K-rough numbers

Page 189: Nbvtalkatbzaonencryptionpuzzles

Assuming k is the required answer. Simplify kn = p, kn = p(kn)(1/n) = p(1/n)k = p(1/n) /* k = pow(p,1/n) */

You can think of using logarithms also. K=log

A program to find out nth root of a number, p.

Page 190: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<math.h>   int main(){     double n,p;     while (scanf("%lf%lf", &n, &p) == 2)         printf("%.0lf\n", pow(p, 1 / n));     return 0; }  

Page 191: Nbvtalkatbzaonencryptionpuzzles

How many digits are there in a given integer?What is the largest integer which is integer power to 10 and divides a given integer?

Page 192: Nbvtalkatbzaonencryptionpuzzles

Guess from the following data?Recall the definition of logarithm.

Page 193: Nbvtalkatbzaonencryptionpuzzles

log10(10)=1log10(99)=1.99999999log10(100)=2log10(999)=2.99999999log10(1000)=3log10(9999)=3.99999999log10(10000)=4log10(99999)=4.99999999log10(100000)=5log10(999999)=5.99999999

Page 194: Nbvtalkatbzaonencryptionpuzzles

A secret code reorders the letters in a message using an array. E.g. the following message "Attack at noon or we are done for" is placed in a 6*6 array :

Attack*at*noon*or*we*are*done*for... Blank letters are replaced by asterisks, and full stops are added to the message so that

it fills out the array. The coded message can then be read down the columns, i.e. A*ow*ftanedott**ora*oan.cnrre.ko*e*. Write a program that will encrypt a message as above. Use an array with 6 columns,

and adjust the number of rows depending on the message length. Example input: Attack at noon or we are done forExample Output: A*ow*ftanedott**ora*oan.cnrre.ko*e*.

An example encryption program.

Page 195: Nbvtalkatbzaonencryptionpuzzles

int main(){ char word[256], mat[50][6]; int j,len,i,k;  scanf("%[^\n]",word); len = strlen(word); for(j=0,i=0; j < len/6; j++) for(k=0;k<6;k++,i++) mat[j][k]=(word[i]==' ')?'*':word[i]; if(len%6){ for(k=0;k<len%6;k++,i++) mat[j][k]=(word[i]==' ')?'*':word[i]; for(i=len%6;i<6;i++)mat[j][i]='.'; j++; } for(i=0;i<6;i++) for(k=0;k<j;k++)printf("%c",mat[k][i]); printf("\n"); return 0;}

Our Solution

Page 196: Nbvtalkatbzaonencryptionpuzzles

General Statement: Odysseus is stranded on an uncharted island in the middle of the Mediterranean Sea. Worse yet, he cannot escape because the Evil Naga, with its über-pointy trident, is guarding the island. Odysseus tried asking for help from Athena, but the Evil Naga simply intercepted all his messages and stopped them from reaching Athena. Odysseus finally devised a simple way to encode his message by removing the overlapping portions between pairs of words to generate a single word. Thinking his message was gibberish, the Evil Naga allowed his message to pass. However, even Athena can’t understand his message! Help her decode Odysseus’ message so she can aid his escape.

  Input: The first line of the input is an integer n that represents the number of data collections that

follow where each data collection contains a pair of strings. The first line of each data collection will contain string a. The second line of each data collection will contain string b. Both strings a and b will contain only the lowercase characters between a and z, inclusive.

Output: Your program should produce n lines of output (one for each data collection). Each line should contain a single string s representing the joining of non-overlapping portions of the two strings a and b. The overlap is determined by the largest value of m such that the last m characters of string a exactly match the first m characters of string b. The output is to be formatted exactly like that for the sample output given below.

Assumptions: The value for n will not exceed 1000.The lengths for strings a b and s each will not exceed 100. All input will be valid.

Sample Input: 3 helpers ersme escapeade ade ody sseus Sample Output: helpme escape odysseus

Odyssean Encryption (Taylor High School Programming Contest November, 2007)

Page 197: Nbvtalkatbzaonencryptionpuzzles

Solution: First, we identify the location (k) of last character of the first string in the second string. Then, we print check last k characters of first string and first k charcters of second string whether they are same or not. If all are same then we print characters of first string except last k characters and we also print characters of second string other than first k characters

Page 198: Nbvtalkatbzaonencryptionpuzzles

int main(){ char x[100],y[100], z[100], res[2048]=""; int i,j,k,n,m,l; scanf("%d",&n);fflush(stdin); while(n--){ scanf("%s",x); fflush(stdin); scanf("%s",y); fflush(stdin); //printf("%s %s\n",x,y); m=strlen(x)-1; k=0; while(y[k]!=x[m]&&y[k]!='\0') k++; for(i=m-k,j=0;j<k;i++,j++) if(x[i]!=y[j]) break; if(y[k]=='\0'){ strcpy(z,x);strcat(z,y); } else{ for(i=0;i<m-k;i++)z[i]=x[i]; for(l=k+1; y[l]!='\0';l++,i++)z[i]=y[l]; z[i]='\0'; } strcat(res,z);strcat(res,"\n"); } printf("%s",res); return 0; }

Page 199: Nbvtalkatbzaonencryptionpuzzles
Page 200: Nbvtalkatbzaonencryptionpuzzles

Sample Input: Hello, Paul. This is John.   Sample Output: Hlo al hsi on el,Pu.Ti sJh. Imp!bm!itj!po dk+Ot-Sh~rIg-   Solution: We read a line full of text into a string variable. First, its

even indexed characters are printed in a line using a for loop, then odd indexed characters of the given string are printed in the following line using another for loop.

  We traverse the characters of the given string and if it is odd

indexed character then it is replaced with its predecessor character; otherwise it is replaced with its successor. Each time, we check whether the replaced characters are in between 32 to 126 or not; if not we adjust them as given in the problem specification.

  Now, given string’s even indexed characters are printed in a line

using a for loop, then odd indexed characters of the given string are printed in the following line using another for loop.

Page 201: Nbvtalkatbzaonencryptionpuzzles

int main(){ int i,n,p; char line[1024],v; scanf("%[^\n]",line); for(i=0;line[i]!='\0';i++)if(i%2==0)printf("%c",line[i]); printf("\n"); for(i=0;line[i]!='\0';i++)if(i%2)printf("%c",line[i]); printf("\n"); for(i=0;line[i]!='\0';i++){v=line[i]; if(i%2==0)v++; else v--; if(v<32)v=126; if(v>126)v=32; line[i]=v; } for(i=0;line[i]!='\0';i++)if(i%2==0)printf("%c",line[i]); printf("\n"); for(i=0;line[i]!='\0';i++)if(i%2)printf("%c",line[i]); printf("\n"); return 0; }

Page 202: Nbvtalkatbzaonencryptionpuzzles

Decoding program.

int main(){ int i,n,p; char line1[1024],line2[1024],v; scanf("%[^\n]",line1);fgetc(stdin); scanf("%[^\n]",line2); i=0; while(line1[i]!='\0'&&line2[i]!='\0'){ v=line1[i]; if(v==32)v=126; else v--; printf("%c",v); v=line2[i]; if(v==126)v=32; else v++; printf("%c",v); i++; } if(line1[i]!='\0') { v=line1[i]; if(v==32)v=126; else v--; printf("%c",v); } else if(line2[i]!='\0') { v=line2[i]; if(v==126)v=32; else v++; printf("%c",v); } printf("\n"); system("PAUSE"); return 0; }

Page 203: Nbvtalkatbzaonencryptionpuzzles
Page 204: Nbvtalkatbzaonencryptionpuzzles

Solution: We propose to use table driven computation. First, few say eleven prime numbers and their cumulative sum is stored in two separate arrays primes and primesums whose size is 256 elements. Remaining elements of these arrays are initialized to zeros. Whenever we want prime numbers sum say till nth prime number, we first check whether nth element of the array primesums is other than zero or not. If other than zero then print its value directly; otherwise by using the functions process() and nestPrime(), we compute the required prime numbers and update arrays primes, primesums before printing the required value. This is useful in reducing re-computing prime numbers. That is, if we want sum of prime numbers till nth prime number where n is more than 10 then we compute next n-11 prime numbers as already first 11 prime numbers are available in the arrays. Also, if we want prime numbers sum till mth prime number where m>n, and m,n>10 then we compute next (m-n) prime numbers as some are already computed with n. Thus, we get computational advantage.

Page 205: Nbvtalkatbzaonencryptionpuzzles

int nextPrime(int n){ while(++n){ if(isPrime(n))break; } return n; } int computesums(int n){ int np,i; for(i=npp;i<=n;i++){ np=nextPrime(primes[i-1]); primes[i]=np; primesums[i]=primesums[i-1]+np; } npp=n; return primesums[n]; } int main(){ int i,n,m,T; char result[20000],res[20]; for(i=11;i<256;i++){primes[i]=0;primesums[i]=0;} scanf("%d",&T); while(T--){ scanf("%d",&n); if(primesums[n]) sprintf(res,"%d\n",primesums[n]); else sprintf(res,"%d\n",computesums(n)); strcat(result,res); } printf("%s\n",result); return 0; }

Page 206: Nbvtalkatbzaonencryptionpuzzles

ROT-13 is a simple algorithm that moves every letter in a string 13 spaces forward in the alphabet. A becomes N, B becomes O, C becomes P, and so on. Similarly, N becomes A, O becomes B, P becomes C, and so on.

  A simple lookup table can be constructed as follows:

CODE, for example, becomes PBQR when run through ROT-13. PBQR becomes CODE when run through ROT-13. The same technique is used for both encoding and decoding.

  This technique is particularly good for obfuscating spoilers. For example, someone who had seen the

film The Empire Strikes Back could post on a newsgroup the phrase "QNEGU INQRE VF YHXR FXLJNYXRE'F SNGURE!" without risk of offending anyone who hadn't yet seen the film.

  Your task is to write a program that applies the ROT-13 algorithm to a given string. The string will be in all

upper-case. Spaces and other characters that aren't letters should be ignored (that is, not encoded or decoded), but still kept as part of the output. The string will not be longer than 500 characters.

  Example 1 (user input shown in bold): Enter the text to encode/decode: THE NUMBER 34 IS WRITTEN "THIRTY FOUR" GUR AHZORE 34 VF JEVGGRA "GUVEGL SBHE"   Example 2 (user input shown in bold): Enter the text to encode/decode: UBARFGYL, JUB UNFA'G FRRA "GUR RZCVER FGEVXRF ONPX" HONESTLY, WHO HASN'T SEEN "THE EMPIRE STRIKES BACK"  

ROT13

Page 207: Nbvtalkatbzaonencryptionpuzzles

A common puzzle is to present a math problem where each digit is replaced by a letter. So, for example the sum:

  112+ 234 346 could be represented as: AAB+BCD CDE where A=1, B=2, C=3, D=4, and E=6. Notice that the same digit always replaces all instances of the

same letter. It will also be the case that each distinct letter will be replaced by a different digit. Your task is to take a problem written as letters, and display the equivalent version using numbers.  Input:There will be several input instances. Each input instance will begin with a number, N, indicating the

number of different letters used in the math problem. A value of N=0 will indicate the end of input. On the next line will be the problem, in the form (for example):

AAB + BCD = CDE. All letters will be capital, and only the first N letters (starting from A) will be used. Each operand (and the sum) will be at most 5 letters long.

 Output:For each input instance, output the equivalent mathematical statement, after replacing letters with

numbers. If there is more than one possible answer for a given input, display the one with the lowest digit for “A”, then the lowest digit for “B”, and so on. If there is no possible way to assign digits legally to solve the problem, then output “No solution possible”

Crypto-Math

Page 208: Nbvtalkatbzaonencryptionpuzzles

Sample Input: 5 AAB + BCD = CDE 9 EFGH + ABCD = BIEF 3 AAA + B = BDDD 4 AAA + B = CDDD 0   Sample Output: 112 + 234 = 346 2769 + 0358 = 3127 999 + 1 = 1000 No solution possible.    

Page 209: Nbvtalkatbzaonencryptionpuzzles

Develop a program that accepts as input two strings, the first of which is ciphertext (i.e., an encoded message) and the second of which is a key that can be used to decode it, and that produces as output theplaintext (i.e., the original message).

The key is a string of four uppercase letters. To decode the first letter of ciphertext, "add" it (see explanation below) to the first letter of the key. Similarly, to decode the second, third, and fourth letters of ciphertext, "add" them to the second, third, and fourth, respectively, letters of the key. Beginning with the fifth letter of ciphertext, use the four letters of the key once more, in the same way. (Thus, the first letter of the key is used for decoding the 1st, 5th, 9th, etc., letters of ciphertext, the second letter of the key is used for decoding the 2nd, 6th, 10th, etc., letters of ciphertext, and similarly for the third and fourth letters of the key.)

To "add" two letters together, add their numeric values together (using A=1, B=2, C=3, ..., Z=26), subtract 26 if the result is greater than 26, and then find the letter having the corresponding numeric value. For example, E + C = H (corresponding to 5 + 3 = 8) and E + X = C (corresponding to 5 + 24 - 26 = 3).

Ciphertext given as input will not include lower case letters. It may, however, include spaces and punctuation marks (e.g., periods, commas, etc.). Upper case letters are to be decoded as described above. Any other characters are assumed to be their own codes. (E.g., The result of decoding a comma is a comma.)

The program should accept input and provide output in the format shown below, repeating until a null string is entered for a message.

Sample Program Execution:Enter Ciphertext: EN UC ENDVCQG!

Enter Key: BALL

Plaintext: GO GO GOPHERS!

Message Decoder

Page 210: Nbvtalkatbzaonencryptionpuzzles

Before the age of computing, some of the simplest codes were sent in plain view, embedded in a long string of text. The simplest type of this embedded code is to “hide” a string of text every ‘n’ characters in the larger block of text. The recipient only needed to know the value of ‘n’, to extract the message.

 You are to write a program that searches a block of text for a given string.

Determine if the string is embedded somewhere, and if so, report the ‘n’ value.

 For example, String to search for: Hello WorldText to search through: AHaealalaoa aWaoaraladResult: “Hello World” is found with encoding of 2. In this problem, case matters. Treat all characters in the string to search for as

significant, including spaces. That is, in the above example, if the text to search through was AhaealalaoaaWaoaralad, then “Hello World” is not found.

Embedded Codes

Page 211: Nbvtalkatbzaonencryptionpuzzles

INPUT: The input file for this program will consist of a series of search pairs. The first line of such a pair will be the string to search for (the embedded code). This line will be no more than 80 characters long and will be terminated by the character “*”. The next (up to) 255 characters will be the text to search through. The character “*” will determine the end of this line. Both the search string and the text to search through will be comprised of alphanumeric characters and the space character. There will be no punctuation, carriage return/line feeds or any other whitespace other than the space character contained in either string. (The file, of course, will contain carriage return/line feeds, but these will not be found in either string.) The end of the input file will be denoted by the “#” character. You may assume the text to search through is at least as long as the string being searched for.

  The input file will be e.dat.   OUTPUT: For each search pair, output one line of text, either: [search string] is not found. Or [search string] is found with encoding of n. where “search string” is replaced with the actual string being searched for, and “n” is

replaced with the integer encoding value.

Page 212: Nbvtalkatbzaonencryptionpuzzles

Sample I/O

Page 213: Nbvtalkatbzaonencryptionpuzzles

J4 Encryption

Page 214: Nbvtalkatbzaonencryptionpuzzles

While working on a paper in the Sampson Hall computer lab one day, you realize that you have forgotten your disk and that you need something to save the files on.  Luckily, one of your theater-major friends is sitting nearby and you ask to borrow her disk.  Unfortunately, you are working on a very important paper for your Programming Languages class and you do not want her to have access to your files.  You decide to come up with an encryption program to ensure that she will not be able to view your document.

The way the encryption works for this is simple.  First, each letter is rotated forwards five locations: A®F, B®G, C®H, etc.  Then, there is a second rotation.  The first letter stays as it is.  Every subsequent letter is rotated backwards.  It’s rotated backwards one location for every letter after A the letter before it is after the second rotation.  For example, if the string after the first rotation ends up being FGHIJ, the F stays put.  The G is rotated backwards five letters to B because the letter F is five locations after A.  This leaves FBHIJ.  The H is then rotated backwards one letter to G because B is one location after A.  This leaves FBGIJ.  The I is rotated backwards 6 locations to C, resulting in FBGCJ.  Finally, the J is rotated backwards 2 locations to H, resulting in the answer FBGCH.

You will be given the document one sentence at a time.  Only the capital letters (there will be no lower-cased letters) need to be rotated.  Punctuation and spaces are to be left as they are originally placed and do not count in the second rotation.  The sentence will be no more than eighty (80) letters long.  You should output to the screen what the final sentence would look like after the encryption.  The program should stop after the sentence entered is only a “*”.

Super Encryptor

Page 215: Nbvtalkatbzaonencryptionpuzzles

NOTE: THESE ARE THE CORRECTED TEST CASES: EXAMPLE: (BOLDFACE INDICATES USER INPUT.) Enter the line to be converted: ABCDE The encrypted line is: FBGCH   Enter the line to be converted: I LIKE TO TYPE The encrypted line is: N DKFE UZ ZEQT   Enter the line to be converted: GO PURPLE ACES!! The encrypted line is: LI MNJLFE BGDU!!

Page 216: Nbvtalkatbzaonencryptionpuzzles

Determine the number of rounds in a dance.

Page 217: Nbvtalkatbzaonencryptionpuzzles

Solution:

Page 218: Nbvtalkatbzaonencryptionpuzzles

FBI Puzzle -2013

Page 219: Nbvtalkatbzaonencryptionpuzzles

Compression vs Encryption

• Compression reduces message size• Encryption: Not to reduce the message size.

Page 220: Nbvtalkatbzaonencryptionpuzzles

Write a program to decode the message which is run length encoded. See the sample input and output. Assume only upper case alphabets

• Sample Input:• 7AB8C12MZ

• Sample Output:• AAAAAAABCCCCCCCCMMMMMMMMMMMMZ

Page 221: Nbvtalkatbzaonencryptionpuzzles

Bit Wise Operators – Low Level Operators

Page 222: Nbvtalkatbzaonencryptionpuzzles

Where they are essential?

• Coding/Encoding• Data Encryption• Hacking• forensics• Device drivers• Instrumentation

Page 223: Nbvtalkatbzaonencryptionpuzzles

Bit-Wise operators

• Unary - ~ (Complement)• Binary –& (AND)| (OR)^ (XOR)<< (Left Shift)>> (Right Shift)

Page 224: Nbvtalkatbzaonencryptionpuzzles

How to turn off least significant bit?• x=x&(~1)x=010110001=00000001~1=1111110X&(~1)= 01011000 11111110 ------------- 01011000X=01011001 then 01011001 11111110 -------------- 01011000

Page 225: Nbvtalkatbzaonencryptionpuzzles

How to turn off right most 1-bit?• x=x&(x-1)x=01011000x-1=01010111X&(x-1)= 01011000 01010111 ------------- 01010000X=01011001 then 01011001 x-1= 01011000 -------------- x&(x-1) 01011000

Page 226: Nbvtalkatbzaonencryptionpuzzles

How to turn off right most 0-bit?• x=x&(x-1)x=01011000x+1=01011001X|(x+1)= 01011000 01011001 ------------- 01011001x=01011001 then 01011001 x+1= 01011010 -------------- x|(x+1) 01011011

Page 227: Nbvtalkatbzaonencryptionpuzzles

x=x&(x+1) X=10101111 X+1=10110000 X&(x+1) = 10101111 10110000 --------- 10100000This can be used to test whether an unsigned

integer is 0 or all 1’s (2^n-1)

To turn off trailing 1’s in a word

Page 228: Nbvtalkatbzaonencryptionpuzzles

X=x|(x-1) X=10100000 X-1=10011111 X|(x-1)=10100000 10011111 -------- 10111111

To turn on the trailing 0’s of a word.

Page 229: Nbvtalkatbzaonencryptionpuzzles

X=10101111 X+1=10110000 ~x=01010000 ~x&(x+1)=01010000 10110000 --------- 00010000

Create a word with a single 1-bit at the rightmost 0-bit in x.x=~x&(x+1)

Page 230: Nbvtalkatbzaonencryptionpuzzles

To create a word with a single 0-bit at the right position of the rightmost 1-bit in x.~x|(x-1)x=10101000x-1=10100111~x=01010111~x|(x-1)=01010111 10100111 --------- 11110111

Page 231: Nbvtalkatbzaonencryptionpuzzles

~x&(x-1) or ~(x|-x) or (x&~x)-1X=01011000~x=10100111X-1=01010111~x&(x-1)=10100111 01010111 -------- 00000111

To create a word with 1’s at the positions of trailing 0s in a word x, and 0s elesewhere.

Page 232: Nbvtalkatbzaonencryptionpuzzles

X=01011000 -x=10100111 1 -------- 10101000 (x|-x) 01011000 10101000 --------- 11111000 ~(x|-x)=00000111

Page 233: Nbvtalkatbzaonencryptionpuzzles

X=01011000 -x=10101000 X&-x=01011000 10101000 --------- 00001000 (x&-x)-1=00001000 -1 --------- 00000111

1

Page 234: Nbvtalkatbzaonencryptionpuzzles

X=~x|(x+1) X=10100111 X+1=10101000 ~x|(x+1)=01011000 10101000 -------- 11111000

To create a word with 0s at the positions of the trailing 1’s and 0s elsewhere.

Page 235: Nbvtalkatbzaonencryptionpuzzles

X=x&(-x) X=01011000 10100111 1 ----------- 10101000

-x=10101000 X&(-x)=01011000 10101000 -------- 00001000

To isolate the rightmost 1-bit.

Page 236: Nbvtalkatbzaonencryptionpuzzles

To create a word with 1’s at the positions of the rightmost 1-bit and the trailing 0s in x.

X^(x-1) X=01011000 X-1=01010111 X^(x-1)=01011000 01010111 --------- 00001111

X=01010011 X-1=01010010 X^(x-1)=01010011 01010010 --------- 00000001

Page 237: Nbvtalkatbzaonencryptionpuzzles

To create a word with 1s at the positions of the rightmost 0-bit and trailing 1s. X=x^(x=1)

X=01010111 X+1=01011000 X^(x+1)=01010111 01011000 -------- 00001111

X=11110000 X+1=11110001 X^(x+1)=11110000 11110001 -------- 00000001

Page 238: Nbvtalkatbzaonencryptionpuzzles

To turn off the rightmost contiguous string of 1s (((x|(x-1))+1)&x) ((x&-x)+x)&x

X=01011100 -x=10100011 1 10100100 X&-x=01011100 10100100 00000100 +x 01011100 01100000 &x 01011100 01000000

Page 239: Nbvtalkatbzaonencryptionpuzzles

if (x & (1<<n)) { n-th bit is set } else { n-th bit is not set }

To test nth bit is set or not.

Page 240: Nbvtalkatbzaonencryptionpuzzles

x=x | (1<<n) X=01010001 N=3 01010001 00001000 01011001

Set nth bit.

Page 241: Nbvtalkatbzaonencryptionpuzzles

x=x & ~(1<<n) X=01010001 N=3 01010001 11110111(~(1<<3)) 01010001

Un-Set nth bit.

Page 242: Nbvtalkatbzaonencryptionpuzzles

Toggle nth bit. x=x ^(1<<n) X=01010001 n=3 01010001 00001000 01011001

X=01011001 00001000 01010001

Page 243: Nbvtalkatbzaonencryptionpuzzles

bool f; // conditional flag unsigned int m; // the bit mask unsigned int w; // the word to modify: //if (f) w |= m; else w &= ~m; w ^= (-f ^ w) & m; //

OR, for superscalar CPUs: w = (w & ~m) | (-f & m);

Conditionally set or clear bits without branching

Page 244: Nbvtalkatbzaonencryptionpuzzles

If you need to negate only when a flag is false, then use the following to avoid branching:

bool fDontNegate; // Flag indicating we should not negate v. int v; // Input value to negate if fDontNegate is false. int r; // result

= fDontNegate ? v : -v; r = (fDontNegate ^ (fDontNegate - 1)) * v; If you need to negate only when a flag is true, then use this: bool fNegate; // Flag indicating if we should negate v. int v; // Input value to negate if fNegate is true. int r; // result = fNegate ? -v : v; r = (v ^ -fNegate) + fNegate;

Conditionally negate a value without branching

Page 245: Nbvtalkatbzaonencryptionpuzzles

//24bitvar r:uint = 0x33;var g:uint = 0x66;var b:uint = 0x99;var color:uint = r << 16 | g << 8 | b;

//32bitvar a:uint = 0xff;var r:uint = 0x33;var g:uint = 0x66;var b:uint = 0x99;var color:uint = a << 24 | r << 16 | g << 8 | b;

Combining color components

Page 246: Nbvtalkatbzaonencryptionpuzzles

Strangely enough, this is 300%(!) faster. i = -i;

//equalsi = ~i + 1;

//ori = (i ^ -1) + 1;

Sign flipping using NOT or XOR

Page 247: Nbvtalkatbzaonencryptionpuzzles

If the divisor is a power of 2, the modulo (%) operation can be done with:modulus = numerator & (divisor – 1);This is about 600% faster.

x = 131 % 4;

//equals:x = 131 & (4 - 1);

Fast modulo operation using bitwise AND

Page 248: Nbvtalkatbzaonencryptionpuzzles

Forget Math.abs() for time critical code. Version 1 is 2500% faster than Math.abs(), and the funky bitwise version 2 is again 20% faster than version 1.

//version 1i = x < 0 ? -x : x;

//version 2i = (x ^ (x >> 31)) - (x >> 31);

Absolute value

Page 249: Nbvtalkatbzaonencryptionpuzzles

int v; // we want to find the absolute value of v

unsigned int r; // the result goes here int const mask = v >> sizeof(int) *

CHAR_BIT - 1; r = (v + mask) ^ mask;

Patented variation: r = (v ^ mask) - mask;

abs() continued

Page 250: Nbvtalkatbzaonencryptionpuzzles

This is 35% faster. eqSign = a * b > 0;

//equals:eqSign = a ^ b >= 0;

Comparing two integers for equal sign

Page 251: Nbvtalkatbzaonencryptionpuzzles

R8 = (R5 << 3) | (R5 >> 2)G8 = (R5 << 3) | (R5 >> 2)B8 = (R5 << 3) | (R5 >> 2)

Fast color conversion from R5G5B5 to R8G8B8 pixel format using shifts

Page 252: Nbvtalkatbzaonencryptionpuzzles

int x, y; // input values to compare signs bool f = ((x ^ y) < 0); // true iff x and y have opposite signs

Detect if two integers have opposite signs

Page 253: Nbvtalkatbzaonencryptionpuzzles

int x; // we want to find the minimum of x and y int y; int r; // the result goes here r = y ^ ((x ^ y) & -(x < y)); // min(x, y) Ex: x=00100110, y=00000011 X^y=00100110 00000011 00100101 X<y=00110000 -(x<y)=11001111 1 11010000 (x^y)&-(x<y)=00100101 11010000 00000000 Y^((x^y)&-(x<y))= 00000011 00000000 00000011(Result)

Compute the minimum (min) of two integers without branching

Page 254: Nbvtalkatbzaonencryptionpuzzles

int x; // we want to find the maximum of x and y int y;

int r; // the result goes here

r = x ^ ((x ^ y) & -(x < y)); // max(x, y)

Compute the maximum (max) of two integers without branching

Page 255: Nbvtalkatbzaonencryptionpuzzles

unsigned int v; // we want to see if v is a power of 2

bool f; // the result goes here f = (v & (v - 1)) == 0; Note that 0 is incorrectly considered a

power of 2 here. To remedy this, use: f = v && !(v & (v - 1));

Determining if an integer is a power of 2

Page 256: Nbvtalkatbzaonencryptionpuzzles

unsigned int v; // we want to see if v is a power of 2

bool f; // the result goes here f = (v & (v - 1)) == 0; Note that 0 is incorrectly considered a

power of 2 here.

To remedy this, use: f = v && !(v & (v - 1));

Determining if an integer is a power of 2

Page 257: Nbvtalkatbzaonencryptionpuzzles

unsigned int a; // value to merge in non-masked bits unsigned int b; // value to merge in masked bits unsigned int mask; // 1 where bits from b should be selected; 0 where

from a. unsigned int r; // result of (a & ~mask) | (b & mask) goes here r = a ^ ((a ^ b) & mask); This saves one operation from the obvious way of

combining two sets of bits according to a bit mask. If the mask is a constant, then there may be no advantage.

Merge bits from two values according to a mask

Page 258: Nbvtalkatbzaonencryptionpuzzles

unsigned int v; // count the number of bits set in v

unsigned int c; // c accumulates the total bits set in v

for (c = 0; v; v >>= 1) { c += v & 1; } The naive approach requires one iteration per

bit, until no more bits are set. So on a 32-bit word with only the high set, it will go through 32 iterations.

Counting bits set (naive way)

Page 259: Nbvtalkatbzaonencryptionpuzzles

Counting bits set by lookup table

Page 260: Nbvtalkatbzaonencryptionpuzzles

#include<math.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> static const unsigned char BitsSetTable256[256] = { # define B2(n) n, n+1, n+1, n+2 # define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2) # define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2) B6(0), B6(1), B6(1), B6(2) }; int main(){ int i; for(i=0;i<256;i++)printf("%d ",BitsSetTable256[i]); system("PAUSE"); return 0; }

Page 261: Nbvtalkatbzaonencryptionpuzzles

Compute parity by lookup table

Page 262: Nbvtalkatbzaonencryptionpuzzles

unsigned int i, j; // positions of bit sequences to swap

unsigned int n; // number of consecutive bits in each sequence

unsigned int b; // bits to swap reside in b unsigned int r;

// bit-swapped result goes here unsigned int x = ((b >> i) ^ (b >> j)) & ((1U << n) - 1);

// XOR temporary r = b ^ ((x << i) | (x << j));

Swapping individual bits with XOR

Page 263: Nbvtalkatbzaonencryptionpuzzles

As an example of swapping ranges of bits suppose we have have b = 00101111 (expressed in binary) and we want to swap the n = 3 consecutive bits starting at i = 1 (the second bit from the right) with the 3 consecutive bits starting at j = 5; the result would be r = 11100011 (binary).

Of course, the result is undefined if the sequences overlap.

Page 264: Nbvtalkatbzaonencryptionpuzzles

unsigned int v; // input bits to be reversed unsigned int r = v; // r will be reversed bits of v; first get LSB of v

int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end for (v >>= 1; v; v >>= 1) { r <<= 1; r |= v & 1; s--; } r <<= s; // shift when v's highest bits are zero

Reverse bits the obvious way

Page 265: Nbvtalkatbzaonencryptionpuzzles

Reverse bits in word by lookup table

Page 266: Nbvtalkatbzaonencryptionpuzzles

unsigned int v; // 32-bit word to find the log base 2 of

unsigned int r = 0; // r will be lg(v) while (v >>= 1) // unroll for more speed... { r++; }

The log base 2 of an integer is the same as the position of the highest bit set (or most significant bit set, MSB).

Find the log base 2 of an integer with the MSB N set in O(N) operations (the obvious way)

Page 267: Nbvtalkatbzaonencryptionpuzzles

unsigned int v; // 32-bit word input to count zero bits on right

unsigned int c = 32; // c will be the number of zero bits on the right

v &= -signed(v); if (v) c--; if (v & 0x0000FFFF) c -= 16; if (v & 0x00FF00FF) c -= 8; if (v & 0x0F0F0F0F) c -= 4; if (v & 0x33333333) c -= 2; if (v & 0x55555555) c -= 1;

Count the consecutive zero bits (trailing) on the right in parallel

Page 268: Nbvtalkatbzaonencryptionpuzzles

unsigned int v; // compute the next highest power of 2 of 32-bit v

v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++;

Round up to the next highest power of 2

Page 269: Nbvtalkatbzaonencryptionpuzzles

unsigned short x; // Interleave bits of x and y, so that all of the unsigned short y; // bits of x are in the even positions and y in the odd; unsigned int z = 0; // z gets the resulting Morton Number. for (int i = 0; i < sizeof(x) * CHAR_BIT; i++) // unroll for more speed... { z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1); } Interleaved bits (aka Morton numbers) are useful for

linearizing 2D integer coordinates, so x and y are combined into a single number that can be compared easily and has the property that a number is usually close to another if their x and y values are close.

Interleave bits the obvious way

Page 270: Nbvtalkatbzaonencryptionpuzzles

We may want to know if any byte in a word has a specific value. To do so, we can XOR the value to test with a word that has been filled with the byte values in which we're interested. Because XORing a value with itself results in a zero byte and nonzero otherwise, we can pass the result to haszero.

#define hasvalue(x,n) \ (haszero((x) ^ (~0UL/255 * (n))))

Determine if a word has a byte equal to n

Page 271: Nbvtalkatbzaonencryptionpuzzles

uppose we have a pattern of N bits set to 1 in an integer and we want the next permutation of N 1 bits in a lexicographical sense. For example, if N is 3 and the bit pattern is 00010011, the next patterns would be 00010101, 00010110, 00011001,00011010, 00011100, 00100011, and so forth. The following is a fast way to compute the next permutation.

unsigned int v; // current permutation of bits unsigned int w; // next permutation of bits

unsigned int t = v | (v - 1); // t gets v's least significant 0 bits set to 1 // Next set to 1 the most significant bit to change, // set to 0 the least significant ones, and add the necessary 1

bits. w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1));

Compute the lexicographically next bit permutation

Page 272: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<stdlib.h> void ND(int n){ if(n/2)ND(n/2); printf("%d",n%2); } int main() { unsigned int v; // current permutation of bits unsigned int w,t; // next permutation of bits scanf("%d",&v); ND(v);printf("\n"); t = v | (v - 1); // t gets v's least significant 0 bits set to 1 // Next set to 1 the most significant bit to change, // set to 0 the least significant ones, and add the necessary 1

bits. w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1)); ND(w);printf("\n"); system("PAUSE"); return 0; }

Page 273: Nbvtalkatbzaonencryptionpuzzles

Another approach

Page 274: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<stdlib.h> void ND(int n){ if(n/2)ND(n/2); printf("%d",n%2); } unsigned snoob(unsigned x){ unsigned smallest, ripple, ones; smallest=x&-x; ripple=x+smallest; ones=x^ripple; ones=(ones>>2)/smallest; return ripple|ones; } int main() { unsigned int v; // current permutation of bits unsigned int w,t; // next permutation of bits scanf("%d",&v); ND(v);printf("\n"); w = snoob(v); ND(w);printf("\n"); system("PAUSE"); return 0; }

Page 275: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<stdlib.h> void ND(int n){ if(n/2)ND(n/2); printf("%d",n%2); } int main() { unsigned int p,q,w; // current permutation of bits scanf("%d%d",&p,&q); ND(p);printf("\n"); ND(q);printf("\n"); w=(p&q)+( (p^q)>>1); ND(w);printf("\n"); system("PAUSE"); return 0; }

Average of two unsigned integers p,q=(p&q)+( (p^q)>>1)

Page 276: Nbvtalkatbzaonencryptionpuzzles

Determination of overflow in unsigned multiplication

Page 277: Nbvtalkatbzaonencryptionpuzzles

Exchanging corresponding fields of a registers

Page 278: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<stdlib.h> void ND(int n){ if(n/2)ND(n/2); printf("%d",n%2); } int main() { unsigned int p,q,w,mask; // current permutation of bits scanf("%d%d",&p,&q); ND(p);printf("\n"); ND(q);printf("\n"); scanf("%d",&mask); w=(p&~mask)|(q&mask); q=(q&~mask)|(p&mask); p=w; ND(p);printf("\n"); ND(q);printf("\n"); system("PAUSE"); return 0; }

Page 279: Nbvtalkatbzaonencryptionpuzzles

Sample output

Page 280: Nbvtalkatbzaonencryptionpuzzles

#include<stdio.h> #include<stdlib.h> void ND(int n){ if(n/2)ND(n/2); printf("%d",n%2); }

int isPalindrome(unsigned x){ unsigned original = x; unsigned reverse = 0; while (x){ reverse <<= 1; reverse += x % 2; //in fact we can do even better x&1 instead of x%2 x >>= 1; } return (reverse == original); } int main() { unsigned int p; // current permutation of bits scanf("%d",&p); ND(p);printf("\n"); isPalindrome(p)?printf("Yes\n"):printf("No\n"); system("PAUSE"); return 0; }

To check whether a numbers binary code represents palindrome or not.

Page 281: Nbvtalkatbzaonencryptionpuzzles

Sum=x^y; carry=(x&y)<<1;

Adding two unsigned integers (x,y) with bit wise operators

Page 282: Nbvtalkatbzaonencryptionpuzzles

Suppose we have a set A = { 1,2,3,4,5 };We would like to print the power set of A.

let N be the size of the set. Size of power set = pow(2, N)In C, C++, (1 << N) is equivalent to computing pow(2, N).

int A[] = {1,2,3,4,5};int N = 5;int Total = 1 << N;for ( int i = 0; i < Total; i++ ){    for ( int j = 0; j < N; j++)        if ( (i >> j) & 1 )            cout << A[j];    cout << endl;}

In fact this is a very widely used technique. Also it is much faster than the recursive version.

This technique could be used to solve the subset sum problem also if the size of the set is small (less than 50).

Generating Power Set

Page 283: Nbvtalkatbzaonencryptionpuzzles

Suppose we have 'n' boys and 'm' girls. Some boys don't like some girls and vice-versa.Lets say we have a boolean matrix valid[i][j] which says if ith boy can be paired with jth girl.We need to know how many ways can 'k' pairs be chosen for a dance competition. 1 <= n,m,k <=10, and k <= min (m , n)

This is a little difficult to explain in layman's words. Nevertheless I will try here.

Let 'mask' be a bitwise array. Each set bit in the mask represents which girls have already been paired with some boys (we dont know who but we are sure that she is paired).

Now read this line very carefully.dp[i][mask] represents number of ways of making pairs using some boys numbered from 1 to i and some girls represented by set bits of mask.This means number of set bits of mask, __builtin_popcount(mask) <= i.Also __builtin_popcount(mask) = number of pairs selected so far.

Dynamic Programming use

Page 284: Nbvtalkatbzaonencryptionpuzzles

memset( dp, 0, sizeof dp );dp[0][0] = 1;for (int i = 0; i < n; i++ ){    for ( int mask = 0; mask < (1 << m); mask++ )    {        dp[i+1][mask] += dp[i][mask];        for( int t = 0; t < m; t++)            if ( (mask >> t) & 1 == 0 && valid[i][t] )                dp[i+1][mask | (1 << t)] += dp[i][mask];    }}

long long ans = 0;for ( int mask = 0; mask < (1 << m); mask++ )    if ( __builtin_popcount(mask) == k )        ans += dp[n][mask];

Variable 'ans' contains the answer to the problem.

The complexity of the whole algorithm is  n * O( 2^m ).

dp[0][0] = 1; //1 way to choose no boys and no girls.

for each set of girls that have been already paired we can do one of the following:

The current boy can be paired with a girl that is not paired. [line 8 to 10] The current boy may not be paired with any girl. [line 7]

Now finally all we need to do is count dp[n][mask] for all those mask whose number of set bits is 'k'.

Page 285: Nbvtalkatbzaonencryptionpuzzles

Basis for Elliptic curve cryptographyy^2=x^3-ax+b

Page 286: Nbvtalkatbzaonencryptionpuzzles

y2 = x3 - x + 1)

Page 287: Nbvtalkatbzaonencryptionpuzzles
Page 288: Nbvtalkatbzaonencryptionpuzzles

max: 115792089210356248762697446949407573530086143415290314195533631308867097853951

curve: y² = x³ + ax + b a =

115792089210356248762697446949407573530086143415290314195533631308867097853948

b = 41058363725152142129326129780047268409114441015993725554835256314039467401291

CloudFlare's ECC curve for ECDHE (This is the same curve used by Google.com):

Page 289: Nbvtalkatbzaonencryptionpuzzles

Thanks