Copyright © 直通硅谷
http://www.zhitongguigu.com/
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Given a number n. Is n a prime?
Copyright © 直通硅谷
http://www.zhitongguigu.com/
A Prime Number can be divided evenly only by 1, or itself.
And it must be a whole number greater than 1.
Input? Output?
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
Given a number n. Is n a prime?
Copyright © 直通硅谷
http://www.zhitongguigu.com/
public boolean isPrime(int n) {
// implement you method here
}
Naive Idea
Copyright © 直通硅谷
http://www.zhitongguigu.com/
public boolean isPrime(int n) {
// Sudo code
int i from 2 -> n-1;
if n mod i == 0
return false
return true
}
How many calculations?
n - 2
Better Idea
Copyright © 直通硅谷
http://www.zhitongguigu.com/
public boolean isPrime(int n) {
// Sudo code
int i from 2 -> n / 2;
if n mod i == 0
return false
return true
}
How many calculations?
n / 2 - 2
Even Better
Copyright © 直通硅谷
http://www.zhitongguigu.com/
public boolean isPrime(int n) {
// Sudo code
int i from 2 -> Math.sqrt(n);
if n mod i == 0
return false
return true
}
How many calculations?
sqrt(n) - 1
Why Square Root Works
Copyright © 直通硅谷
http://www.zhitongguigu.com/
If n = a * b, then n is not a prime
If we cannot find such a (b), then n is a prime
If Math.sqrt(n) = m = 3.316, then a <= m <= b
Do we really care about b?
Conclusion: check from 2 to Math.sqrt(n)
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Suppose 1 calculation is 1ms
input n | (n-2) | sqrt(n) - 1: |
---|---|---|
10 | 8ms | 2ms |
10^10 | 10^10ms = 115 days | 10^5ms = 1.66mins |
Homework:
Implement the above 2
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Big O notation
Copyright © 直通硅谷
http://www.zhitongguigu.com/
If both and are right, we need to give
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Best Example: Quick Sort
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Copyright © 直通硅谷
http://www.zhitongguigu.com/
T(n) = T(n-1) + cn
T(n-1) = T(n-2) + c(n-1)
...
T(1) = T(0) + c
T(0) = 0
Copyright © 直通硅谷
http://www.zhitongguigu.com/
T(n) = T(n-1) + cn
T(n-1) = T(n-2) + c(n-1)
...
T(1) = T(0) + c
T(0) = 0
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Example: Binary Search T(n) = T(n/2) + m
a = 1, b = 2, c = 0
It fits the second condition. So T(n) = logn
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Count Primes
Copyright © 直通硅谷
http://www.zhitongguigu.com/
Count the number of prime numbers less than a non-negative number, n.