Stuck In Run Mode Jupyter Notebook - jupyter

My Jupyter Notebook gets stuck in run mode whenever i run the shell with the following code:
def is_prime(num):
if num < 2:
return False
for x in range(2, num - 1):
if num % x == 0:
return False
return True
prime_list = []
num = 2
while True:
if is_prime(num):
prime_list.append(num)
num += 1
if len(prime_list) == 10002:
break
print(prime_list[-1])
Could someone please run this code on their computer and tell me what the output is? I'd really appreciate any answer.

Your code is getting stuck because your prime testing function becomes very slow!
I ran your code with varying stopping points of 100, 1000, 2000, and 4000 prime numbers found. The runs took 0.01, 0.23, 0.98, and 4.31 seconds, respectively.
You can see that doubling the number of primes to find (roughly) quadruples the amount of time taken. This makes sense, given that to test if n is prime, you have to check it against n-2 other numbers (you exclude 1 and n). So, your algorithm has a time complexity of at least O(n^2) to find n prime numbers.
(also, I got 104759 after 10002 prime numbers were found in 30 seconds. I accidentally typed "100002" at first, which sat running for quite a long time without any results...)

Related

How does this prime number checking function work

Can anybody please help me how this code works,
I am not getting it by myself, some help would be greatly appreciated.
Prime number in scala using recusion:
def isPrime(n: Int): Boolean = {
def isPrimeUntil(t: Int): Boolean =
if (t<=1) true
else n%t != 0 && isPrimeUntil(t-1)
isPrimeUntil(n/2)
}
The number n is prime if and only if there's no number t such that t != 1, t!= n, n % t = 0.
So, if you find some number from 2 to n-1 such that n % t = 0, n is composite, otherwise it is prime.
One more thing, you may see that there's no need to search for divisors among the numbers greater than n/2.
So, all the algorithm does is checks n % d for each t from n/2 to 2. As soon as it is found, the algorithms stops ans says it's composite (returns False). Otherwise it gets to t = 1 and assures the number is prime (returns True).
Just to mention, it's enough to consider the numbers from ceil(sqrt(n)) to 2, which results in better time complexity (O(sqrt(n)) vs O(n)).
isPrime(7) --> isPrimeUntil(3) --> (3 <= 1)? no
(7%3 != 0)? yes
isPrimeUntil(2) --> (2 <= 1)? no
(7%2 != 0)? yes
isPrimeUntil(1) --> (1 <= 1)? yes
isPrime(7) is true. No divisor was found between 1 and 7/2.
isPrime(9) --> isPrimeUntil(4) --> (4 <= 1)? no
(9%4 != 0)? yes
isPrimeUntil(3) --> (3 <= 1)? no
(9%3 != 0)? no
isPrime(9) is false. Found that 9 is divisible by 3.
If you have a local Scala REPL, you should paste this function in there and play around with it. If not, there's always Scastie. I made a Scastie snippet, in which I changed the formatting to my liking, added comments and a demo range.
There are examples of Scala that make it look almost like Malbolge. This one is not that bad.
Let's follow it through with a composite number like 102. Calling isPrime(102) causes isPrimeUntil(51) to be invoked (as 51 is half 102). Since 51 is greater than 1, the nested function calculated 102 % 51, which is 0, so, by "short-circuit evaluation" of logical AND, the nested function should return false.
Now let's try it with 103. Calling isPrime(103) causes isPrimeUntil(51) to be invoked (as 51 is half 103 and the remainder of 1 is simply discarded). Since 51 is greater than 1, the nested function calculated 103 % 51, which is 1, so the nested function calls itself as primeUntil(50). Since 50 is greater than 1, the... so on and so forth until calling itself as primeUntil(1). Since t == 1, primeUntil returns true and the recursion stops.
This gives the wrong answer for negative composite numbers. Plus, as others have mentioned, it is inefficient to start the recursion at n/2. This would be an improvement:
def isPrime(n: Int): Boolean = {
def isPrimeUntil(t: Int): Boolean = {
if (t <= 1) true else n % t != 0 && isPrimeUntil(t - 1)
}
isPrimeUntil(Math.floor(Math.sqrt(Math.abs(n))).toInt)
}
Hmm... it's still giving the wrong answer for −1, 0, 1. But hopefully now you understand this function.

Palindrome Explanation

I encountered the following in a leetcode article to determine whether an integer is a palindrome
Now let's think about how to revert the last half of the number. For number 1221, if we do 1221 % 10, we get the last digit 1, to get the second to the last digit, we need to remove the last digit from 1221, we could do so by dividing it by 10, 1221 / 10 = 122. Then we can get the last digit again by doing a modulus by 10, 122 % 10 = 2, and if we multiply the last digit by 10 and add the second last digit, 1 * 10 + 2 = 12, it gives us the reverted number we want. Continuing this process would give us the reverted number with more digits.
Now the question is, how do we know that we've reached the half of the number?
Since we divided the number by 10, and multiplied the reversed number by 10, when the original number is less than the reversed number, it means we've processed half of the number digits.
Can someone explain the last two sentences please?! Thank you!
Here is the enclosed C# code:
public class Solution {
public bool IsPalindrome(int x) {
// Special cases:
// As discussed above, when x < 0, x is not a palindrome.
// Also if the last digit of the number is 0, in order to be a palindrome,
// the first digit of the number also needs to be 0.
// Only 0 satisfy this property.
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
// For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
// since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
return x == revertedNumber || x == revertedNumber/10;
}
}
The reason is due to the original given input, x will be decreasing by 1 digit while the reverted string increases by 1 digit at the same time. The process keeps on going until x is less than or equal to the reverted string. Hence due to the change length changes, when it terminates, we would approximately reach half of the string.
Let's visit a few examples with positive numbers to understand the process. I would write (x,y) as the (original number, reverted string). The third example is purposely designed to show that it need not be exactly half though but the code would still work.
The first example is 1221, where there are even number of digits. It will go from (1221, 0) to (122, 1) to (12, 12), at this stage, the two terms are equal and hence the process terminates and we can conclude that it is a palindrome.
The next example is 1223, where there are even number of digits. It will go from (1223, 0) to (122, 3) to (12, 32), at this stage, the termination condition holds and hence the process terminates and we can conclude that it is not a palindrome.
Now, the third example is 1211,then the sequence is (1211,0), (121, 1), (12,11), (1,112), after which we terminates from the string and it would conclude that it is not a palindrome
Now, let's make the number consists of odd number of digits:
For 12321. It will go from (12321, 0) to (1232, 1) to (123, 12) to (12, 123) and at this point, the condition breaks. We then divide the reverted string by 10 and we end up with (12,12) and we can conclude that it is a palindrome.
For 12323. It will go from (12323, 0) to (1232, 3) to (123, 32) to (12, 323) and at this point, the condition breaks. We then divide the reverted string by 10 and we end up with (12,32) and we can conclude that it is not a palindrome.
For 12311. It will go from (12311, 0) to (1231, 1) to (123, 11) to (12, 113) and at this point, the condition breaks. We then divide the reverted string by 10 and we end up with (12,11) and we can conclude that it is not a palindrome.
I hope these examples would help you to understand what the post mean.

truncatingRemainder(dividingBy: ) returning nonZero remainder even if number is completely divisible

I am trying to get remainder using swift's truncatingRemainder(dividingBy:) method.
But I am getting a non zero remainder even if value I am using is completely divisible by deviser. I have tried number of solutions available here but none worked.
P.S. values I am using are Double (Tried Float also).
Here is my code.
let price = 0.5
let tick = 0.05
let remainder = price.truncatingRemainder(dividingBy: tick)
if remainder != 0 {
return "Price should be in multiple of tick"
}
I am getting 0.049999999999999975 as remainder which is clearly not the expected result.
As usual (see https://floating-point-gui.de), this is caused by the way numbers are stored in a computer.
According to the docs, this is what we expect
let price = //
let tick = //
let r = price.truncatingRemainder(dividingBy: tick)
let q = (price/tick).rounded(.towardZero)
tick*q+r == price // should be true
In the case where it looks to your eye as if tick evenly divides price, everything depends on the inner storage system. For example, if price is 0.4 and tick is 0.04, then r is vanishingly close to zero (as you expect) and the last statement is true.
But when price is 0.5 and tick is 0.05, there is a tiny discrepancy due to the way the numbers are stored, and we end up with this odd situation where r, instead of being vanishingly close to zero, is vanishing close to tick! And of course the last statement is then false.
You'll just have to compensate in your code. Clearly the remainder cannot be the divisor, so if the remainder is vanishingly close to the divisor (within some epsilon), you'll just have to disregard it and call it zero.
You could file a bug on this but I doubt that much can be done about it.
Okay, I put in a query about this and got back that it behaves as intended, as I suspected. The reply (from Stephen Canon) was:
That's the correct behavior. 0.05 is a Double with the value 0.05000000000000000277555756156289135105907917022705078125. Dividing 0.5 by that value in exact arithmetic gives 9 with a remainder of 0.04999999999999997501998194593397784046828746795654296875, which is exactly the result you're seeing.
The only rounding error that occurs in your example is in the division price/tick, which rounds up to 10 before your .rounded(.towardZero) has a chance to take effect. We'll add an API to let you do something like price.divided(by: tick, rounding: .towardZero) at some point, which will eliminate this rounding, but the behavior of truncatingRemainder is precisely as intended.
You really want to have either a decimal type (also on the list of things to do) or to scale the problem by a power of ten so that your divisor become exact:
1> let price = 50.0
price: Double = 50
2> let tick = 5.0
tick: Double = 5
3> let r = price.truncatingRemainder(dividingBy: tick)
r: Double = 0

In count change recursive algorithm, why do we return 1 if the amount = 0?

I am taking coursera course and,for an assignment, I have written a code to count the change of an amount given a list of denominations. A doing a lot of research, I found explanations of various algorithms. In the recursive implementation, one of the base cases is if the amount money is 0 then the count is 1. I don't understand why but this is the only way the code works. I feel that is the amount is 0 then there is no way to make change for it and I should throw an exception. The code look like:
function countChange(amount : Int, denoms :List[Int]) : Int = {
if (amount == 0 ) return 1 ....
Any explanation is much appreciated.
To avoid speaking specifically about the Coursera problem, I'll refer to a simpler but similar problem.
How many outcomes are there for 2 coin flips? 4.
(H,H),(H,T),(T,H),(T,T)
How many outcomes are there for 1 coin flip? 2.
(H),(T)
How many outcomes are there for 0 coin flips? 1.
()
Expressing this recursively, how many outcomes are there for N coin flips? Let's call it f(N) where
f(N) = 2 * f(N - 1), for N > 0
f(0) = 1
The N = 0 trivial (base) case is chosen so that the non-trivial cases, defined recursively, work out correctly. Since we're doing multiplication in this example and the identity element for multiplication is 1, it makes sense to choose that as the base case.
Alternatively, you could argue from combinatorics: n choose 0 = 1, 0! = 1, etc.

Calculating prime numbers in Scala: how does this code work?

So I've spent hours trying to work out exactly how this code produces prime numbers.
lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =>
ps.takeWhile{j => j * j <= i}.forall{ k => i % k > 0});
I've used a number of printlns etc, but nothings making it clearer.
This is what I think the code does:
/**
* [2,3]
*
* takeWhile 2*2 <= 3
* takeWhile 2*2 <= 4 found match
* (4 % [2,3] > 1) return false.
* takeWhile 2*2 <= 5 found match
* (5 % [2,3] > 1) return true
* Add 5 to the list
* takeWhile 2*2 <= 6 found match
* (6 % [2,3,5] > 1) return false
* takeWhile 2*2 <= 7
* (7 % [2,3,5] > 1) return true
* Add 7 to the list
*/
But If I change j*j in the list to be 2*2 which I assumed would work exactly the same, it causes a stackoverflow error.
I'm obviously missing something fundamental here, and could really use someone explaining this to me like I was a five year old.
Any help would be greatly appreciated.
I'm not sure that seeking a procedural/imperative explanation is the best way to gain understanding here. Streams come from functional programming and they're best understood from that perspective. The key aspects of the definition you've given are:
It's lazy. Other than the first element in the stream, nothing is computed until you ask for it. If you never ask for the 5th prime, it will never be computed.
It's recursive. The list of prime numbers is defined in terms of itself.
It's infinite. Streams have the interesting property (because they're lazy) that they can represent a sequence with an infinite number of elements. Stream.from(3) is an example of this: it represents the list [3, 4, 5, ...].
Let's see if we can understand why your definition computes the sequence of prime numbers.
The definition starts out with 2 #:: .... This just says that the first number in the sequence is 2 - simple enough so far.
The next part defines the rest of the prime numbers. We can start with all the counting numbers starting at 3 (Stream.from(3)), but we obviously need to filter a bunch of these numbers out (i.e., all the composites). So let's consider each number i. If i is not a multiple of a lesser prime number, then i is prime. That is, i is prime if, for all primes k less than i, i % k > 0. In Scala, we could express this as
nums.filter(i => ps.takeWhile(k => k < i).forall(k => i % k > 0))
However, it isn't actually necessary to check all lesser prime numbers -- we really only need to check the prime numbers whose square is less than or equal to i (this is a fact from number theory*). So we could instead write
nums.filter(i => ps.takeWhile(k => k * k <= i).forall(k => i % k > 0))
So we've derived your definition.
Now, if you happened to try the first definition (with k < i), you would have found that it didn't work. Why not? It has to do with the fact that this is a recursive definition.
Suppose we're trying to decide what comes after 2 in the sequence. The definition tells us to first determine whether 3 belongs. To do so, we consider the list of primes up to the first one greater than or equal to 3 (takeWhile(k => k < i)). The first prime is 2, which is less than 3 -- so far so good. But we don't yet know the second prime, so we need to compute it. Fine, so we need to first see whether 3 belongs ... BOOM!
* It's pretty easy to see that if a number n is composite then the square of one of its factors must be less than or equal to n. If n is composite, then by definition n == a * b, where 1 < a <= b < n (we can guarantee a <= b just by labeling the two factors appropriately). From a <= b it follows that a^2 <= a * b, so it follows that a^2 <= n.
Your explanations are mostly correct, you made only two mistakes:
takeWhile doesn't include the last checked element:
scala> List(1,2,3).takeWhile(_<2)
res1: List[Int] = List(1)
You assume that ps always contains only a two and a three but because Stream is lazy it is possible to add new elements to it. In fact each time a new prime is found it is added to ps and in the next step takeWhile will consider this new added element. Here, it is important to remember that the tail of a Stream is computed only when it is needed, thus takeWhile can't see it before forall is evaluated to true.
Keep these two things in mind and you should came up with this:
ps = [2]
i = 3
takeWhile
2*2 <= 3 -> false
forall on []
-> true
ps = [2,3]
i = 4
takeWhile
2*2 <= 4 -> true
3*3 <= 4 -> false
forall on [2]
4%2 > 0 -> false
ps = [2,3]
i = 5
takeWhile
2*2 <= 5 -> true
3*3 <= 5 -> false
forall on [2]
5%2 > 0 -> true
ps = [2,3,5]
i = 6
...
While these steps describe the behavior of the code, it is not fully correct because not only adding elements to the Stream is lazy but every operation on it. This means that when you call xs.takeWhile(f) not all values until the point when f is false are computed at once - they are computed when forall wants to see them (because it is the only function here that needs to look at all elements before it definitely can result to true, for false it can abort earlier). Here the computation order when laziness is considered everywhere (example only looking at 9):
ps = [2,3,5,7]
i = 9
takeWhile on 2
2*2 <= 9 -> true
forall on 2
9%2 > 0 -> true
takeWhile on 3
3*3 <= 9 -> true
forall on 3
9%3 > 0 -> false
ps = [2,3,5,7]
i = 10
...
Because forall is aborted when it evaluates to false, takeWhile doesn't calculate the remaining possible elements.
That code is easier (for me, at least) to read with some variables renamed suggestively, as
lazy val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i =>
ps.takeWhile{p => p * p <= i}.forall{ p => i % p > 0});
This reads left-to-right quite naturally, as
primes are 2, and those numbers i from 3 up, that all of the primes p whose square does not exceed the i, do not divide i evenly (i.e. without some non-zero remainder).
In a true recursive fashion, to understand this definition as defining the ever increasing stream of primes, we assume that it is so, and from that assumption we see that no contradiction arises, i.e. the truth of the definition holds.
The only potential problem after that, is the timing of accessing the stream ps as it is being defined. As the first step, imagine we just have another stream of primes provided to us from somewhere, magically. Then, after seeing the truth of the definition, check that the timing of the access is okay, i.e. we never try to access the areas of ps before they are defined; that would make the definition stuck, unproductive.
I remember reading somewhere (don't recall where) something like the following -- a conversation between a student and a wizard,
student: which numbers are prime?
wizard: well, do you know what number is the first prime?
s: yes, it's 2.
w: okay (quickly writes down 2 on a piece of paper). And what about the next one?
s: well, next candidate is 3. we need to check whether it is divided by any prime whose square does not exceed it, but I don't yet know what the primes are!
w: don't worry, I'l give them to you. It's a magic I know; I'm a wizard after all.
s: okay, so what is the first prime number?
w: (glances over the piece of paper) 2.
s: great, so its square is already greater than 3... HEY, you've cheated! .....
Here's a pseudocode1 translation of your code, read partially right-to-left, with some variables again renamed for clarity (using p for "prime"):
ps = 2 : filter (\i-> all (\p->rem i p > 0) (takeWhile (\p->p^2 <= i) ps)) [3..]
which is also
ps = 2 : [i | i <- [3..], and [rem i p > 0 | p <- takeWhile (\p->p^2 <= i) ps]]
which is a bit more visually apparent, using list comprehensions. and checks that all entries in a list of Booleans are True (read | as "for", <- as "drawn from", , as "such that" and (\p-> ...) as "lambda of p").
So you see, ps is a lazy list of 2, and then of numbers i drawn from a stream [3,4,5,...] such that for all p drawn from ps such that p^2 <= i, it is true that i % p > 0. Which is actually an optimal trial division algorithm. :)
There's a subtlety here of course: the list ps is open-ended. We use it as it is being "fleshed-out" (that of course, because it is lazy). When ps are taken from ps, it could potentially be a case that we run past its end, in which case we'd have a non-terminating calculation on our hands (a "black hole"). It just so happens :) (and needs to ⁄ can be proved mathematically) that this is impossible with the above definition. So 2 is put into ps unconditionally, so there's something in it to begin with.
But if we try to "simplify",
bad = 2 : [i | i <- [3..], and [rem i p > 0 | p <- takeWhile (\p->p < i) bad]]
it stops working after producing just one number, 2: when considering 3 as the candidate, takeWhile (\p->p < 3) bad demands the next number in bad after 2, but there aren't yet any more numbers there. It "jumps ahead of itself".
This is "fixed" with
bad = 2 : [i | i <- [3..], and [rem i p > 0 | p <- [2..(i-1)] ]]
but that is a much much slower trial division algorithm, very far from the optimal one.
--
1 (Haskell actually, it's just easier for me that way :) )