Bloomberg LP Interview Question
Software Engineer / DevelopersYou are not required to generate a 9 digit prime. You only want to verify if it is a prime. So, generating a list of all primes is unnecessary here.
Generate a random 9 digit number. Split it into xx, xxx, xxxx and xxx-xx-xxxx. Pass these four numbers to the function that verifies if a number is prime or not. AND the result of the four method calls return the result.
To test if a number n is prime, divide n with [1, sqrt(n)] and if any one produces a remainder of 0, the number is not prime.
how to generate a 9 digits random number?
RAND_MAX varies between compilers and can be as low as 32767
randomly generate 4 digits 2 digits 3 digits then put them together?
any other solutions?
Find all prime numbers in [1,999999999], and put these numbers in a set. Look up xxx,xx,xxxx and xxx-xx-xxxx in this set. Before that, a preprocessing is needed to get the integer number of xxx,xx,xxxx and xxx-xx-xxxx. For example, The xxx could be 010, so the real number is 10.
- Xiao January 27, 2010To find all prime numbers between [7,n]:
int prime[] = {1,3,5};
int total = 3;
int gap = 2;
for(i = 7; i <= n; i+=gap){
gap = 6-gap;
int j = 1;
bool flag = true;
while(prime[j]^2 < i){
if (i%prime[j] == 0){
flag = false;
break;
}
}
if(flag == true){
prime[total++] = i;
}
}