## shahsunny712

BAN USER- 0 Answers
**Removing even/odd numbers in problem 5.7 of cracking the coding interview**Following is problem 5.7 (under Bit Manipulation) in the 5th edition of Cracking the coding interview:

- shahsunny712 May 14, 2015

An array A[1..n] contains all the integers from 0 to n except for one number which is missing. In this problem, we cannot access an entire integer in A with a single opera-tion. The elements of A are represented in binary, and the only operation we can use to access them is “fetch the jth bit of A[i]”, which takes constant time. Write code to find the missing integer. Can you do it in O(n) time?

The algorithm applied is this:

1. Start with LSB.

2. Count occurrence of 1's vs 0's.

If count(1) < count(0) it means the missing number has a 1 as it's LSB, else it has a 0.

3. Remove all numbers with LSB not matching result found in step 3.

4. Repeat steps 1 to 4, and progressively checking the next LSB in each iteration.

Can someone explain the logic behind step 3? It basically removes all odd/even numbers from the current list (depending on the bit found for the missing number) and uses the modified list in the next iteration. Why do we do this?| Flag | PURGE - 4 Answers
**Finding all prime numbers within a given range**This is problem PRIME1 from SPOJ:

- shahsunny712 June 30, 2014

Input:

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

Output:

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

To solve this, I applied a variation of the sieve of eratosthenes to calculate all primes from 2 to the maximum input number. Then iterate over that list and print out the numbers for each test case.

However, this gives TLE when the maximum input is 100000000(the allowed max). At several online forums, I read that to solve this, one needs to calculate primes only upto sqrt(100000000). I don't understand why this should work. Won't there be primes in the range say, 10000000 - 100000000 which are much greater than 100000000 ?| Flag | PURGE

**CareerCup**is the world's biggest and best source for software engineering interview preparation. See all our resources.

Open Chat in New Window

Ah! I saw it on algorithmist which is a pretty good site otherwise.

- shahsunny712 July 01, 2014There is a limit on memory and code size, but I suppose I can fit it in.