# Math
本小节总结一些与数学(尤其是数论部分)有关的基础,主要总结了《挑战程序设计竞赛》第二章。
### 最大公约数(GCD, Greatest Common Divisor)
常用的方法为辗转相除法,也称为欧几里得算法。不妨设函数`gcd(a, b)`是自然是`a`, `b`的最大公约数,不妨设`a > b`, 则有 a=b×p+qa = b \times p + qa=b×p+q, 那么对于`gcd(b, q)`则是`b`和`q`的最大公约数,也就是说`gcd(b, q)`既能整除`b`, 又能整除`a`(因为 a=b×p+qa = b \times p + qa=b×p+q, `p`是整数),如此反复最后得到`gcd(a, b) = gcd(c, 0)`, 第二个数为0时直接返回`c`. 如果最开始`a < b`, 那么`gcd(b, a % b) = gcd(b, a) = gcd(a, b % a)`.
关于时间复杂度的证明:可以分`a > b/2`和`a < b/2`证明,对数级别的时间复杂度,过程略。
与最大公约数相关的还有最小公倍数(LCM, Lowest Common Multiple), 它们两者之间的关系为 lcm(a,b)×gcd(a,b)=∣ab∣ lcm(a, b) \times gcd(a, b) = |ab|lcm(a,b)×gcd(a,b)=∣ab∣.
### Java
~~~
public static long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
~~~
### Problem
给定平面上两个坐标 P1=(x1, y1), P2=(x2,y2), 问线段 P1P2 上除 P1, P2以外还有几个整数坐标点?
#### Solution
问的是线段 P1P2, 故除 P1,P2以外的坐标需在 x1,x2,y1,y2范围之内,且不包含端点。在两端点不重合的前提下有:
y−y1x−x1=y2−y1x2−x1\frac{y-y_1}{x-x_1}=\frac{y_2 - y_1}{x_2 - x_1}x−x1y−y1=x2−x1y2−y1那么若得知 M=gcd(x2−x1,y2−y1)M = gcd(x_2 - x_1, y_2 - y_1)M=gcd(x2−x1,y2−y1), 则有 x−x1x - x_1x−x1 必为 x2−x1/Mx_2 - x_1 / Mx2−x1/M 的整数倍大小,又因为 x1<x<x2 x_1 < x < x_2x1<x<x2, 故最多有 M−1M - 1M−1个整数坐标点。
### 扩展欧几里得算法
求解整系数 xxx 和 yyy 满足 d=gcd(a,b)=ax+byd = gcd(a, b) = ax + byd=gcd(a,b)=ax+by, 仿照欧几里得算法,应该要寻找 gcd(b,a%b)=bx′+(a%b)y′gcd(b, a \% b) = bx^\prime + (a \% b)y^\primegcd(b,a%b)=bx′+(a%b)y′.
### Java
~~~
public class Solution {
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int[] gcdExt(int a, int b) {
if (b == 0) {
return new int[] {a, 1, 0};
} else {
int[] vals = gcdExt(b, a % b);
int d = vals[0];
int x = vals[2];
int y = vals[1];
y -= (a / b) * x;
return new int[] {d, x, y};
}
}
public static void main(String[] args) {
int a = 4, b = 11;
int[] result = gcdExt(a, b);
System.out.printf("d = %d, x = %d, y = %d.\n", result[0], result[1], result[2]);
}
}
~~~
### Problem
求整数 xxx 和 yyy 使得 ax+by=1ax+by=1ax+by=1.
#### Solution
不妨设`gcd(a, b) = M`, 那么有 M(a′x+b′y)=1M(a^\prime x+b^\prime y)=1M(a′x+b′y)=1 ==> a′x+b′y=1/Ma^\prime x+b^\prime y=1/Ma′x+b′y=1/M 如果 M 大于1,由于等式左边为整数,故等式不成立,所以要想题中等式有解,必有`gcd(a, b) = 1`.
**扩展提:题中等式右边为1,假如为2又会怎样?**
提示:此时c=k⋅gcd(a,b),x′=k⋅x==>c % gcd(a,b)==0c = k \cdot gcd(a, b), x^\prime = k\cdot x ==> c\ \%\ gcd(a, b) == 0c=k⋅gcd(a,b),x′=k⋅x==>c % gcd(a,b)==0, c 为等式右边的正整数值。详细推导见 [How to find solutions of linear Diophantine ax + by = c?](http://math.stackexchange.com/questions/20717/how-to-find-solutions-of-linear-diophantine-ax-by-c)
- Preface
- Part I - Basics
- Basics Data Structure
- String
- Linked List
- Binary Tree
- Huffman Compression
- Queue
- Heap
- Stack
- Set
- Map
- Graph
- Basics Sorting
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
- Bucket Sort
- Counting Sort
- Radix Sort
- Basics Algorithm
- Divide and Conquer
- Binary Search
- Math
- Greatest Common Divisor
- Prime
- Knapsack
- Probability
- Shuffle
- Basics Misc
- Bit Manipulation
- Part II - Coding
- String
- strStr
- Two Strings Are Anagrams
- Compare Strings
- Anagrams
- Longest Common Substring
- Rotate String
- Reverse Words in a String
- Valid Palindrome
- Longest Palindromic Substring
- Space Replacement
- Wildcard Matching
- Length of Last Word
- Count and Say
- Integer Array
- Remove Element
- Zero Sum Subarray
- Subarray Sum K
- Subarray Sum Closest
- Recover Rotated Sorted Array
- Product of Array Exclude Itself
- Partition Array
- First Missing Positive
- 2 Sum
- 3 Sum
- 3 Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Merge Sorted Array
- Merge Sorted Array II
- Median
- Partition Array by Odd and Even
- Kth Largest Element
- Binary Search
- Binary Search
- Search Insert Position
- Search for a Range
- First Bad Version
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Peak Element
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- Median of two Sorted Arrays
- Sqrt x
- Wood Cut
- Math and Bit Manipulation
- Single Number
- Single Number II
- Single Number III
- O1 Check Power of 2
- Convert Integer A to Integer B
- Factorial Trailing Zeroes
- Unique Binary Search Trees
- Update Bits
- Fast Power
- Hash Function
- Count 1 in Binary
- Fibonacci
- A plus B Problem
- Print Numbers by Recursion
- Majority Number
- Majority Number II
- Majority Number III
- Digit Counts
- Ugly Number
- Plus One
- Linked List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Remove Duplicates from Unsorted List
- Partition List
- Two Lists Sum
- Two Lists Sum Advanced
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle II
- Reverse Linked List
- Reverse Linked List II
- Merge Two Sorted Lists
- Merge k Sorted Lists
- Reorder List
- Copy List with Random Pointer
- Sort List
- Insertion Sort List
- Check if a singly linked list is palindrome
- Delete Node in the Middle of Singly Linked List
- Rotate List
- Swap Nodes in Pairs
- Remove Linked List Elements
- Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Maximum Depth of Binary Tree
- Balanced Binary Tree
- Binary Tree Maximum Path Sum
- Lowest Common Ancestor
- Invert Binary Tree
- Diameter of a Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Subtree
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Serialization
- Binary Search Tree
- Insert Node in a Binary Search Tree
- Validate Binary Search Tree
- Search Range in Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Binary Search Tree Iterator
- Exhaustive Search
- Subsets
- Unique Subsets
- Permutations
- Unique Permutations
- Next Permutation
- Previous Permuation
- Unique Binary Search Trees II
- Permutation Index
- Permutation Index II
- Permutation Sequence
- Palindrome Partitioning
- Combinations
- Combination Sum
- Combination Sum II
- Minimum Depth of Binary Tree
- Word Search
- Dynamic Programming
- Triangle
- Backpack
- Backpack II
- Minimum Path Sum
- Unique Paths
- Unique Paths II
- Climbing Stairs
- Jump Game
- Word Break
- Longest Increasing Subsequence
- Palindrome Partitioning II
- Longest Common Subsequence
- Edit Distance
- Jump Game II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Distinct Subsequences
- Interleaving String
- Maximum Subarray
- Maximum Subarray II
- Longest Increasing Continuous subsequence
- Longest Increasing Continuous subsequence II
- Graph
- Find the Connected Component in the Undirected Graph
- Route Between Two Nodes in Graph
- Topological Sorting
- Word Ladder
- Bipartial Graph Part I
- Data Structure
- Implement Queue by Two Stacks
- Min Stack
- Sliding Window Maximum
- Longest Words
- Heapify
- Problem Misc
- Nuts and Bolts Problem
- String to Integer
- Insert Interval
- Merge Intervals
- Minimum Subarray
- Matrix Zigzag Traversal
- Valid Sudoku
- Add Binary
- Reverse Integer
- Gray Code
- Find the Missing Number
- Minimum Window Substring
- Continuous Subarray Sum
- Continuous Subarray Sum II
- Longest Consecutive Sequence
- Part III - Contest
- Google APAC
- APAC 2015 Round B
- Problem A. Password Attacker
- Microsoft
- Microsoft 2015 April
- Problem A. Magic Box
- Problem B. Professor Q's Software
- Problem C. Islands Travel
- Problem D. Recruitment
- Microsoft 2015 April 2
- Problem A. Lucky Substrings
- Problem B. Numeric Keypad
- Problem C. Spring Outing
- Microsoft 2015 September 2
- Problem A. Farthest Point
- Appendix I Interview and Resume
- Interview
- Resume