Find all numbers only divisible by 3, 5 and 7 - math

I was asked on an interview to find all numbers only divisible by 3, 5 and 7. I purposed we can make check like
if (num%3==0 || num%5==0 || num%7==0)
return true
else
return false.
But in this case if we have 6 it will pass the test but its also divisible by 2 so this doesn't work. Can you purpose something?
I am using java. Find mean to check if some number is divisible only to this number

I would approach this by removing all of the factors of 3, 5, and 7 from the original number, and seeing what's left.
while(num % 3 == 0)
{
num = num / 3;
}
while(num % 5 == 0)
{
num = num / 5;
}
while(num % 7 == 0)
{
num = num / 7;
}
return (num == 1);

I won't give you a Java algorithm, as it should be fairly easy to implement.
You can just:
1. check if (n%3 == 0)
2. if it is, set n /= 3 and repeat step 1.
3. do the same for the number 5 and 7
4. now if n != 1, return false, else return true
In a Java algorithm:
// n is some random natural number
if (n == 1 || n == 0)
return false
while (!n%3)
{
n /= 3;
}
while (!n%5)
{
n /= 5;
}
while (!n%7)
{
n /= 7;
}
if (n == 1)
{
return true;
}
else
{
return false;
}
It's not the best syntax, I'm just giving an straight-forward implementation of the algorithm presented above.

We first note that 1 is a member of the set. Although it is not divisible by 3, 5 or 7, neither is it divisible by any number other than 3, 5 or 7, so we will say that 1 is in the set. This conforms to the mathematical definition of the set { x = 3i · 5j · 7k | i, j, k ≥ 0 }.
One method is to count from 1, adding 2 at each step, and checking if the number is divisible only by 3, 5 and 7. That's slow because it does a lot of work that immediately gets discarded, since there are many fewer numbers divisible only by 3, 5 and 7 than there are odd numbers.
A better approach is to generate the desired numbers directly, by induction. The number 1 is in the set, and for any x in the set, so are 3 x, 5 x and 7 x. So the algorithm to generate all numbers divisible only by 3, 5 and 7, in order, is:
1. Initialize a priority queue with the number 1.
2. Pop the smallest number in the priority queue, call it x.
3. Add 3x, 5x and 7x to the priority queue.
4. Output x as the next integer in the set.
5. If you want more output, go to Step 2.
6. Halt.
I implemented both algorithms; you can see them at http://ideone.com/YwnAQ8. The brute-force method takes a little over ten seconds to find the 203 members of the 3,5,7 set less than a million; the priority queue does the same calculation in a hundredth of a second, a thousand times faster. The priority queue implementation used there is explained at my blog. You can also see the set of 3,5,7 numbers at OEIS.

Related

Prime factorization of factorial

Is it possible to find prime factors of factorial without actually calculating the factorial?
My point here is to find prime factors of factorial not of a big number. Your algorithm should skip the step of having to calculate the factorial and derive prime factors from n! where n <= 4000.
Calculating the factorial and finding it's prime divisors is pretty easy, but my program crashes when the input is greater than n=22. Therfore I thought it would be pretty convinent to do the whole process without having to calculate the factorial.
function decomp(n){
var primeFactors = [];
var fact = 1;
for (var i = 2; i <= n; i++) {
fact = fact * i;
}
while (fact % 2 === 0) {
primeFactors.push(2);
fact = fact/2;
}
var sqrtFact = Math.sqrt(fact);
for (var i = 2; i <= sqrtFact; i++) {
while (fact % i === 0) {
primeFactors.push(i);
fact = fact/i;
}
}
return primeFactors;
}
I don't expect any code nor links, exemplifactions and a brief outline is enough.
Let's consider an example: 10! = 2^8 * 3^4 * 5^2 * 7^1. I computed that by computing the factors of each number from 2 to 10:
2: 2
3: 3
4: 2,2
5: 5
6: 2,3
7: 7
8: 2,2,2
9: 3,3
10: 2,5
Then I just counted each factor. There are eight 2's (1 in 2, 2 in 4, 1 in 6, 3 in 8, and 1 in 10), four 3's (1 in 3, 1 in 6, and 2 in 9), two 5's (1 in 5, and 1 in 10), and one 7 (in 7).
In terms of writing a program, just keep an array of counters (it only needs to be as large as the square root of the largest factorial you want to factor) and, for each number from 2 to the factorial, add the count of its factors to the array of counters.
Does that help?

Dynamic Programming: Child running up a staircase

I'm starting to practice Dynamic Programming and I just can't wrap my head around this question:
Question:
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.
The solution from the cracking the coding interview book is like this:
"If we thought about all the paths to the nth step, we could just build them off the paths to the three previous steps. We can get up to the nth stop by any of the following:
Going to the (n-1) step and hopping 1 step
Going to the (n-2) step and hopping 2 steps
Going to the (n-3) step and hopping 3 steps"
Therefor to find the solution you just add the number of these path together !
That's what loses me ! Why isn't the answer like this: add number of those paths then add 3 ? Since if you are on step n-1 or n-2 or n-3, there are 3 ways to get the nth step? I understand that if you write down the answers for the first 4 bases cases (assuming that n=0 returns 1) You can see the fibonacci-like pattern. But you may not also see it so it's difficult.
And then they came up with this code:
public static int countWaysDP(int n, int[] map) {
if (n < 0)
return 0;
else if (n == 0)
return 1;
else if (map[n] > -1)
return map[n];
else {
map[n] = countWaysDP(n - 1, map) + countWaysDP(n - 2, map) + countWaysDP(n - 3, map);
return map[n]; }
}
So my second question. How does it return 1 when n == 0. Even if I accept that fact, I still can't figure out a way to solve it if I return 0 when n == 1.
Hope this makes sense.
Thank you
Here is how I wrapped my head around this-
From the book -
On the very last hop, up to the nth step, the child could have
done either a single, double, or triple step hop. That is, the last
move might have been a single step hop from step n-1, a double
step hop from step n-2, or a triple step hop from n-3. The
total number of ways of reaching the last step is therefore the sum of
the number of ways of reaching each of the last three steps
You are correctly contemplating -
Why isn't the answer like this: add number of those paths then add 3 ?
Since if you are on step n-1 or n-2 or n-3, there are 3 ways to get
the nth step?
The problem with such a base case is that it will be applicable only if n >= 3. You clearly will not add 3 if there are only 2 steps.
Let's break down the individual cases and understand what exactly is the base case here.
n=0
There are no stairs to climb.
Total number of ways = 0
n=1
Total number of ways = 1StepHop from (n-1)
Number of ways to do 1StepHop from Step 0(n-1) = 1
Total number of ways = 1
n=2
Total number of ways = 2StepHop from (n-2) + 1StepHop from (n-1)
Number of ways to do 2StepHop to reach Step 2 from Step 0(n-2) = 1
Number of ways to do 1StepHop to reach Step 2 from Step 1(n-1) = 1 (Previous answer for n=1)
Total number of ways = 1 + 1 = 2
n=3
Total number of ways = 3StepHop from (n-3) + 2StepHop from (n-2) + 1StepHop from (n-1)
Number of ways to do 3StepHop to reach Step 3 from Step 0(n-3) = 1
Number of ways to do 2StepHop to reach Step 3 from Step 1(n-2) = 2 (From previous answer for n = 2)
Number of ways to do 1StepHop to reach Step 3 from Step 2 = 1 (From previous answer for n=1)
Total number of ways = 1 + 2 + 1 = 4
Observation -
As you can see from above, we are correctly accounting for the last step in each case. Adding one for each of -> 1StepHop from n-1, 2StepHop from n-2 and 3StepHop from n-3.
Now looking at the code, the case where we return 1 if n==0 is a bit counter-intuitive since we already saw that the answer should be 0 if n==0. -
public static int countWaysDP(int n, int[] map) {
if (n < 0)
return 0;
else if (n == 0)
return 1; <------------- this case is counter-intuitive
else if (map[n] > -1)
return map[n];
else {
map[n] = countWaysDP(n - 1, map) + countWaysDP(n - 2, map) + countWaysDP(n - 3, map);
return map[n];
}
From the observation, you can see that this counter intuitive case of n==0 is actually the one which is accounting for the final step - 1StepHop from n-1, 2StepHop from n-2 and 3StepHop from n-3.
So hitting n==0 case makes sense only during recursion - which will happen only when the initial value of n is greater than 0.
A more complete solution to this problem may have a driver method which handles that case outside of the core recursive algorithm -
int countWays(int n) {
if (n <= 0 ) return 0;
int[] map = new int[n+1];
for(int i = 0; i<n+1; i++){
map[i] = -1;
}
return countWaysDP(n, map);
}
Hope this is helpful.
You can find the solution on
https://github.com/CrispenGari/Triple-Step-Algorithim/blob/master/main.cpp .
int count_Ways(int n){
if(n<0){
return 0;
}else if(n==0){
return 1;
}else{
return count_Ways(n-1) +count_Ways(n-2) + count_Ways(n-3);
}
}
int main(){
cout<<"Enter number of stairs: ";
int n;
cin>>n;
cout<<"There are "<< count_Ways(n)<<" possible ways the child can run up
thestairs."<<endl;
return 0;
}

Dividing two integers, giving the integer quotient and remainder without dividing or multiplying in R

inspired by these posts:
stackoverflow post 1, stackoverflow post 2, geeksforgeeks post
I wanted to write an algorithm in R to divide two integers, giving the integer quotient and remainder without dividing or multiplying.
However, I am struggling to translate the code to R. Here is what I got so far:
Division_alternative <- function(dividend, divisor) {
# Calculate sign of divisor
if (dividend < 0 | divisor < 0) {
sign <- -1
} else {
sign <- 1
}
# Transform to positive
dividend = abs(dividend)
divisor = abs(divisor)
# Initialize the quotient
quotient = 0
while (dividend >= divisor) {
print(sign*quotient)
dividend - divisor
quotient + 1 }
}
a = 25
b = 4
print(Division_alternative(a, b))
I am not sure what is wrong with the code thus far, that it wouldn't return anything. Anyone a clue?
Using proper assignment and making our function return something, we get:
Division_alternative <- function(dividend, divisor) {
##Handle only positive cases
stopifnot((dividend > 0 && divisor >0))
quotient = 0
while (dividend >= divisor) {
# print(sign*quotient)
dividend <- dividend - divisor
quotient <- quotient + 1 }
return(list(dividend, quotient))
}
a = 25
b = 4
print(Division_alternative(a, b))
I am only handling the positive cases since it is the easiest case. I'll let you figure the logic on how to make it work in the other 3 cases since that's a) the fun in doing those things, b) I am not a CS major and never implemented a modulus and remainder function from scratch.

Confused about prime number checking function

I came across a question on stack overflow about how to check if a number is prime. The answer was the code below. The function int is_prime(int num) returns 1 when the number is prime 0 is returned otherwise.
int is_prime(int num)
{
if (num <= 1) return 0;
if (num % 2 == 0 && num > 2) return 0;
for(int i = 3; i < num / 2; i+= 2)
{
if (num % i == 0)
return 0;
}
return 1;
}
All the logic in the if statements makes sense to me except for the for loop expressions. I don't get why the division i < num / 2 happens and why i+= 2 is being used. Sure one is there to advance the counter and the other is to halt the loop. but why half the number and why increment by two. Any reasonable explanation will be appreciated. Thanks.
Regarding the loop's increment:
The second if (if (num % 2 == 0)) checks if the number is even, and terminates the function if it is. If the function isn't terminated, we know that it's odd, and thus, may only be divisible by other odd numbers. Hence, the loop starts at 3 and checks the number against a series of odd numbers - i.e., increments the potential divisor by 2 on each iteration.
Regarding the loop's stop condition:
The smallest integer larger than 1 is 2. Thus, the largest integer that could ever divide an integer n is n/2. Thus, the loop works it's way up to num/2. If it didn't find a divisor for num by the time it reaches num/2, it has no chance to ever find such a divisor, so it's pointless to keep on going.

Determining the big Oh for (n-1)+(n-1)

I have been trying to get my head around this perticular complexity computation but everything i read about this type of complexity says to me that it is of type big O(2^n) but if i add a counter to the code and check how many times it iterates per given n it seems to follow the curve of 4^n instead. Maybe i just misunderstood as i placed an count++; inside the scope.
Is this not of type big O(2^n)?
public int test(int n)
{
if (n == 0)
return 0;
else
return test(n-1) + test(n-1);
}
I would appreciate any hints or explanation on this! I completely new to this complexity calculation and this one has thrown me off the track.
//Regards
int test(int n)
{
printf("%d\n", n);
if (n == 0) {
return 0;
}
else {
return test(n - 1) + test(n - 1);
}
}
With a printout at the top of the function, running test(8) and counting the number of times each n is printed yields this output, which clearly shows 2n growth.
$ ./test | sort | uniq -c
256 0
128 1
64 2
32 3
16 4
8 5
4 6
2 7
1 8
(uniq -c counts the number of times each line occurs. 0 is printed 256 times, 1 128 times, etc.)
Perhaps you mean you got a result of O(2n+1), rather than O(4n)? If you add up all of these numbers you'll get 511, which for n=8 is 2n+1-1.
If that's what you meant, then that's fine. O(2n+1) = O(2⋅2n) = O(2n)
First off: the 'else' statement is obsolete since the if already returns if it evaluates to true.
On topic: every iteration forks 2 different iterations, which fork 2 iterations themselves, etc. etc. As such, for n=1 the function is called 2 times, plus the originating call. For n=2 it is called 4+1 times, then 8+1, then 16+1 etc. The complexity is therefore clearly 2^n, since the constant is cancelled out by the exponential.
I suspect your counter wasn't properly reset between calls.
Let x(n) be a number of total calls of test.
x(0) = 1
x(n) = 2 * x(n - 1) = 2 * 2 * x(n-2) = 2 * 2 * ... * 2
There is total of n twos - hence 2^n calls.
The complexity T(n) of this function can be easily shown to equal c + 2*T(n-1). The recurrence given by
T(0) = 0
T(n) = c + 2*T(n-1)
Has as its solution c*(2^n - 1), or something like that. It's O(2^n).
Now, if you take the input size of your function to be m = lg n, as might be acceptable in this scenario (the number of bits to represent n, the true input size) then this is, in fact, an O(m^4) algorithm... since O(n^2) = O(m^4).

Resources