This PPT discusses about some programming puzzles that are related to Encryption and also it emphasis the need for strengthening bit-wise operators concept.
4. 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.
8. 10% of the questions are related to Number
theory, especially prime numbers
7-8% of the questions are related to
encryption.
9.
10. 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
14. He considered his work is pure and never
considered as “useful”.
15.
16. 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.)
17.
18.
19. 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.”
20. Sriram Srinivasan
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
21. Sriram Srinivasan
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
22. Sriram Srinivasan
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
23. 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
24. 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 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;
}
26. 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.
27.
28. #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;
}
29.
30. 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.
31.
32.
33.
34. 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 divisors
p array with nr elements representing the prime divisors
pow array with nr elements representing the primes’ powers
THIS IS A MAXIMUM PROBLEM.
35. #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;
}
36. 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
37. r
r1r
r = a % b
a
b
b
r % r1 = 0. gcd (a,b) = r1
r1 = b % r
1
2
3
38. Proof that r1 divides a and b
r1 | r
b = r1 + r
r1 | b
a = qb + r
r1 | b
r1 | r
r1 | a
39. Proof that r1 is the greatest divisor
Say, c | a and c | b
c | qb + r
c | r
c | q’b + r1
c | r1
40. 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.
41. 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
42. 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
43. 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
44. 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
45. 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
46. 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)
47. 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
48. 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
49. 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)
50. 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)
51. 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
52. 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)
53. 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
54. 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
55. 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
56. 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
57. 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)
58. 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
59. If gcd(a,n) = 1, af(n) 1 (mod n)
Consider x1, x2, … xf(n) < n and coprime to n
Since 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)
60. 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
61.
62. 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.
63. 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
64. 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
65. 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)
66. 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}
67. 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)
68. c = m
e (mod n) c m
e (mod n)
c
d m
ed (mod n)
Consider, m
ed (mod p) and m
ed (mod q)
If p | m, m
ed (mod p) = 0 = m (mod p)
If not, m
ed (mod p) m
1+kf(n) (mod p)
m. m
kf(p) f(q) (mod p)
m. (m
f(p))
kf(q) (mod p)
m. (1)
kf(q) (mod p) (by euler)
m (mod p)
69. So, in both cases, m
ed m (mod p)
Similarly, m
ed m (mod q)
m
ed m (mod pq) (chinese remainder theorem)
m (mod n)
m
ed (mod n) = m
70. Creating a big random prime
n = pq
f(n) = (p - 1) (q - 1)
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));
71. Select e coprime to f(n)
Select d, such that ed 1 (mod f(n))
e = new BigInteger("3");
while(phi.gcd(e).intValue() > 1)
e = e.add(new BigInteger("2"));
d = e.modInverse(phi);
73. 73
print pack"C*", split/D+/,
`echo "16iII*oU@{$/=$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 keys
Now: can export RSA except to embargoed destinations
87. Answer:
Use some modular arithmetic, for example 38
≡ 2 (mod12), that is the difference between
38 and 2 is a multiple of 12
88. Answer:
None of them! All permutations of 135 are
multiples of 3.
89. Answer:
12343. Two odds add up to an even, so one
of the primes must be 2.
90. 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.
91. 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.
92.
93. Answer:
base 2: 10
base 3: 201
base 4: 103
base 5: 4302
Base 10: 987654103
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127. 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.
128. 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.
129. 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.
130. 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.
131. 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), and
s=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.
139. 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
140. 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
141. med (mod n) = mde (mod n)
Bob encrypts his name using private key
Alice, the recipient, decrypts it using Bob’s
public key
142. 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
143. 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
144. 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
145. 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.
147. 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.
148. › 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
149. › 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.
150. 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
151. 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.
152.
153. 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
154.
155.
156.
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:
2
72 30
Sample Output:
30
157. Solution: Here, we need to decompose a number into its prime factors. For
this a function prime_decomp is written which returns
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 divisors
pow1: array with nr elements representing the primes’ powers
Also, 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.
160. 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
166. 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.
Input
The input will be an integer N, (0 <= N <= 1000000000).
Output
The output will be the largest prime substring of N. If none of the substrings are
prime, then output “No Primes”
Example 1
2319
Output 1
31
Example 2
2486
Output 2
No Primes
167. 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.
168. 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("%ldn",BestPrime);
else
printf("No Primesn");
return 0;
}
169. 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.
170. 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
171. 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.
172. 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;
}
173. 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.
174. 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;
}
177. 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 88
22 1906
Output from test data:
0
0
178. 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 Output
There is no input to this program. Output should
consist of a single line as shown below, with
<number> replaced by the number computed.
Sample output
The 1500'th ugly number is <number>.
179. 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.
Input
Input 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.
Output
Output 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 input
5
53
0
Sample output
5! = 3 1 1
53! = 49 23 12 8 4 4 3 2 2 1 1 1 1 1 1
1
180.
181. 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
182.
183.
184. 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:
2010
2012
2011
20000012
Output for Sample input:
84
27
0
54296
185. 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
186. 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)
187.
188. 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.
189. 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
194. 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*no
on*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 for
Example Output: A*ow*ftanedott**ora*oan.cnrre.ko*e*.
196. 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
197. 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
200. 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.
204. 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.
206. 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"
207. 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”
209. 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!
210. 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 World
Text to search through: AHaealalaoa aWaoaralad
Result: “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.
211. 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.
212.
213.
214. 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 “*”.
215. 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!!
220. 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
224. How to turn off least significant bit?
• x=x&(~1)
x=01011000
1=00000001
~1=1111110
X&(~1)= 01011000
11111110
-------------
01011000
X=01011001 then 01011001
11111110
--------------
01011000
225. How to turn off right most 1-bit?
• x=x&(x-1)
x=01011000
x-1=01010111
X&(x-1)= 01011000
01010111
-------------
01010000
X=01011001 then 01011001
x-1= 01011000
--------------
x&(x-1) 01011000
226. How to turn off right most 0-bit?
• x=x&(x-1)
x=01011000
x+1=01011001
X|(x+1)= 01011000
01011001
-------------
01011001
x=01011001 then 01011001
x+1= 01011010
--------------
x|(x+1) 01011011
227. x=x&(x+1)
X=10101111
X+1=10110000
X&(x+1) = 10101111
10110000
---------
10100000
This can be used to test whether an unsigned
integer is 0 or all 1’s (2^n-1)
243. 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);
244. 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;
245. //24bit
var r:uint = 0x33;
var g:uint = 0x66;
var b:uint = 0x99;
var color:uint = r << 16 | g << 8 | b;
//32bit
var 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;
246. Strangely enough, this is 300%(!) faster.
i = -i;
//equals
i = ~i + 1;
//or
i = (i ^ -1) + 1;
247. 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);
248. 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 1
i = x < 0 ? -x : x;
//version 2
i = (x ^ (x >> 31)) - (x >> 31);
249. 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;
250. This is 35% faster.
eqSign = a * b > 0;
//equals:
eqSign = a ^ b >= 0;
252. int x, y;
// input values to compare signs
bool f = ((x ^ y) < 0);
// true iff x and y have opposite signs
253. 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)
254. 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)
255. 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));
256. 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));
257. 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.
258. 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.
262. 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));
263. 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.
264. 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
265.
266. 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).
267. 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;
268. 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++;
269. 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.
270. 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))))
271. 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));
272. #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;
}
273.
274. #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;
}
282.
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).
283. 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.
284. 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'.