def GetPrimes(n):
"""
Get all primes up to n.
Use sieve of Eratosthenes to generate all primes less or equal to n. For
example, given n = 10, then returns a list of primes [2, 3, 5, 7].
Args:
n: An integer representing the upper bound.
Returns:
A list containing all primes <= n in the increasing order.
"""
sqrt_n = int(math.sqrt(n))
visited = [False] * (n + 1)
for i in range(2, sqrt_n + 1):
if not visited[i]:
for j in range(i * i, n + 1, i):
visited[j] = True
primes = []
for i in range(2, n + 1):
if not visited[i]:
primes.append(i)
return primes
2019年11月1日 星期五
[Python] GetPrimes code snippet
GetPrimes code snippet:
[Python] ModExponentiation code snippet
ModExponentiation code snippet:
def ModExponentiation(b, e, m):
"""
Modular exponentiation algorithm of time complexity = O(log(e)).
Args:
b: An integer representing the base.
e: An integer representing the exponent.
m: An integer representing modulus.
Returns:
An integer c = b^e (mod m).
"""
if e == 0:
return 1
y = b
output = 1
while e > 0:
if e & 1 == 1:
output = (output * y) % m
y = (y * y) % m
e >>= 1
return output
2019年10月31日 星期四
[Note] Totient summatory function in sublinear time
Original post: https://math.stackexchange.com/questions/316376/how-to-calculate-these-totient-summation-sums-efficiently
Background:
- Totient summatory function: Wolfram
Python code snippet:
class TotientSummatoryFunction():
"""Totient summatory function class."""
def __init__(self, bound, mod):
"""Initialize.
Args:
bound: An integer.
mod: An integer.
"""
self.mod = mod
self.small_values = None
self.small_value_bound = None
self.big_values = {}
self.InitSmallValues(bound)
def InitSmallValues(self, bound):
"""Initialize small values for totient summatory function.
Args:
bound: An integer.
"""
n = 3 * int(math.pow(bound, 2 / 3))
assert(n**3 >= bound**2)
print('InitSmallValues({n})'.format(n=n))
phi = [i for i in range(n + 1)]
for i in range(2, n + 1):
if phi[i] != i:
continue
for j in range(i, n + 1, i):
phi[j] = phi[j] // i * (i - 1)
self.small_values = [0 for i in range(n + 1)]
self.small_values[1] = phi[1] % self.mod
for i in range(2, n + 1):
self.small_values[i] = (self.small_values[i - 1] + phi[i]) % self.mod
self.small_value_bound = n
def Get(self, n):
"""Get totient summatory function value.
Args:
n: An integer.
Returns:
An integer.
"""
if n <= self.small_value_bound:
return self.small_values[n]
if n not in self.big_values:
result = n * (n + 1) // 2
m = self.IntegerSqrt(n)
for d in range(1, m + 1):
result -= self.Get(d) * (n // d - n // (d + 1))
for k in range(2, n // (m + 1) + 1):
result -= self.Get(n // k)
self.big_values[n] = result % self.mod
return self.big_values[n]
def IntegerSqrt(self, n):
"""
Get the integer part of Sqrt[n].
Args:
n: An integer.
Returns:
An integer.
"""
guess = (n >> n.bit_length() // 2) + 1
result = (guess + n // guess) // 2
while abs(result - guess) > 1:
guess = result
result = (guess + n // guess) // 2
while result * result > n:
result -= 1
return result
2019年10月19日 星期六
[Note] Dynamic programming on ProjectEuler
Latest revised on 2019-10-21
General rule:
Examples:
General rule:
Time complexity = Number of states * Number of transitions of one state * Time complexity of transition function
Examples:
2019年10月16日 星期三
2019年10月12日 星期六
[Leetcode] 1170. Compare Strings by Frequency of the Smallest Character
1. Pre-calculated on words.
2. Counting sort and built-in quick-sort (need to know the average/worst time complexity of quick sort.)
3. Binary search of time complexity O(log(n)). Stick on single implementation.
Source code:
2. Counting sort and built-in quick-sort (need to know the average/worst time complexity of quick sort.)
3. Binary search of time complexity O(log(n)). Stick on single implementation.
- left-closed and right-open interval. Same as for loop.
- < in while loop.
- mid = lower + (upper - lower) / 2 to avoid overflow.
- return lower.
You can develop other various implementations based on this one.
Source code:
class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
int[] sorted = new int[words.length];
for (int i = 0; i < words.length; i++) {
sorted[i] = calculate(words[i]);
}
Arrays.sort(sorted);
int[] nums = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
int target = calculate(queries[i]);
int lower = 0;
int upper = words.length;
while (lower < upper) {
int mid = lower + (upper - lower) / 2;
if (sorted[mid] <= target) {
lower = mid + 1;
} else {
upper = mid;
}
}
nums[i] = words.length - lower;
}
return nums;
}
private int calculate(String word) {
int[] counting = new int[26];
for (char c : word.toCharArray()) {
counting[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (counting[i] > 0) {
return counting[i];
}
}
return 0;
}
}
2019年4月24日 星期三
Notes on Google interview
Recommended video: How to: Work at Google — Example Coding/Engineering Interview [link].
How Google hire: https://careers.google.com/how-we-hire/
How Google hire: https://careers.google.com/how-we-hire/
- Apply
- Show your resume in LinkedIn. (Excellent suggestion from my ex-director.)
- Internal referral.
- Interview
- 到龍山寺拜文昌帝君
- Practice LeetCode problems systematically.
- Try to get any feedback after any interview. It will make you better and better.
- Decide
- 文昌帝君會托夢給 hiring committee.
訂閱:
文章 (Atom)