Author: Xiao Fu Ge
Blog: https://bugstack.cn
Precipitate, share, and grow, so that you and others can gain something! 😄
I. Introduction
How close is mathematics to programmers?
Either ifelse or for loop, the code can be said to be the specific realization . So programmers who type code almost cannot do without mathematics, and the difficulty is different.
Then can't you write code if you are not good at math😳? No, you can also write code, you can write more CRUD
. Then, don’t always think that the product requirements are simple, so your implementation process has become addition, deletion, modification, and inspection. It is often because you do not have the ability to implement scalable, easy-to-maintain, and high-performance code implementation solutions that make you young. Wrote more CRUD
!
Compared with small workshops that buy and sell awl, big factories and super big factories pay more attention to mathematical ability.
In 2004, , a huge billboard suddenly appeared on Highway 101, the traffic artery of Silicon Valley, on which was a math problem: {the first 10 prime numbers in the continuous number of e} .com.
Advertisement: Here e is a mathematical constant, the base of natural logarithms, infinite and non-cyclic decimals. The meaning of this question is to find the first 10 prime numbers in e, and then you can get a URL. Enter this website and you will see the second math problem that Google has given you. you successfully unlock this step, Google will tell you that 160a1c726d3478 we may be like-minded people. You can send your resume to this email address and we will make some changes. Things in the world.
calculate e value can be derived by Taylor formula: e^x≈1 + x + x^2/2! + x^3/3! +……+ x^n/n! (1) The derivation calculation process also includes the Sieve of Eratosthenes,
linear screening method. Interested friends can use code to achieve it.
Two, programming exercises
1. Fibonacci sequence
@Test
public void test_Fibonacci() {
int month = 15; // 15个月
long f1 = 1L, f2 = 1L;
long f;
for (int i = 3; i < month; i++) {
f = f2;
f2 = f1 + f2;
f1 = f;
System.out.println("第" + i + "个月的兔子对数: " + f2);
}
}
- Difficulty : ⭐⭐⭐⭐⭐
- Question : There is a pair of rabbits, starting from the third month after birth, they will give birth to a pair of rabbits every month, and the little rabbit will give birth to a pair of rabbits every month after the third month. If the rabbits are not dead, ask each What is the total number of rabbits in a month?
- logic : F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2)
- extension : Fibonacci sequence (Fibonacci sequence) , also known as the golden section sequence, introduced by the mathematician Leonardo Fibonacci (Leonardoda Fibonacci) as an example of rabbit reproduction, so it is also called "Rabbit sequence" refers to such a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... In mathematics, the Fibonacci sequence is recursively as follows Method definition: F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) (n ≥ 2, n ∈ N*) in modern physics, standard In the fields of crystal structure and chemistry, Fibonacci numbers have direct applications. For this reason, the American Mathematical Society has published a mathematics magazine named "Fibonacci Numbers Quarterly" since 1963 for special purposes. Publish the research results in this area.
2. Determine prime numbers
@Test
public void test_Prime() {
int count = 0;
for (int i = 101; i < 200; i++) {
boolean b = true;// 默认此数就素数
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
b = false; // 此数不是素数
break;
}
}
if (b) {
count++;
System.out.print(i + " ");
}
}
System.out.println("\n素数的个数:" + count);
}
- difficulty : ⭐⭐⭐
- Question : Determine how many prime numbers are between 101-200, and output all prime numbers.
- Logic : The method of judging a prime number is to use a number to divide 2 to sqrt (the number). If it can be divisible, it means that the number is not a prime number, otherwise it is a prime number.
- extended : Prime numbers are also called prime numbers, and the number of prime numbers is infinite. There is a classic proof in Euclid's "Elements of Geometry". It uses a common method of proof: the method of proof by contradiction. The specific proof is as follows: Assume that there are only finite n prime numbers, arranged in order from small to large as p1, p2,..., pn, set N=p1×p2×……×pn, then, is a prime number or not a prime number.
3. Number of daffodils
@Test
public void test_narcissus() {
for (int num = 101; num < 1000; num++) {
int bbb = num / 100;
int bb = (num % 100) / 10;
int b = (num % 100) % 10;
if ((bbb * bbb * bbb + bb * bb * bb + b * b * b) == num) {
System.out.println(num);
}
}
}
- Difficulty : ⭐⭐⭐⭐
- title : Print out all the "narcissus numbers". The so-called "narcissus number" refers to a three-digit number whose cube sum is equal to the number itself. For example: 153 is a "daffodil number", because 153 = 1 cube + 5 cube + 3 cube.
- logic : Use the for loop to control 100-999 numbers, and each number is decomposed into units, tens, and hundreds.
- extension : Narcissistic number (Narcissistic number) is also known as pluperfect digital invariant (PPDI), narcissistic number, self-power number, Armstrong number or Armstrong number (Armstrong number), Narcissus Flower number refers to a 3-digit number, and the sum of the powers of 3 of each digit is equal to itself (for example: 1^3 + 5^3+ 3^3 = 153).
4. Decompose prime factors
@Test
public void test_ZhiYinShu() {
f(200);
}
int k = 2;
public void f(int n) {
while (k <= n) {
if (k == n) {
System.out.println(n);
break;
} else if (n > k && n % k ==
System.out.print(k + "*")
n = n / k;
f(n);
break;
} else if (n > k && n % k !=
k++;
f(n);
break;
}
}
}
- difficulty : ⭐⭐⭐⭐
- Topic : Decompose a positive integer into prime factors. For example: input 90 and print out 90=2 3 3*5.
- logic : To decompose the prime factor of n, first find the smallest prime number k, and then follow this step to complete (1) If the prime number is exactly equal to n, it means that the process of decomposing prime factors has ended, just print it out. (2) If n>k, but n is divisible by k, you should print out the value of k and divide n by the quotient of k as a new positive integer, and repeat the first step. (3) If n is not divisible by k, use k+1 as the value of k, and repeat the first step.
- extension : Each composite number can be written in the form of multiplying several prime numbers, and each prime number is a factor of this composite number. Expressing a composite number in the form of multiplying prime factors is called decomposing prime factors. For example, 30=2×3×5. Decomposing prime factors is only for composite numbers.
5. Yanghui Triangle
@Test
public void test_YangHuiSanJiao(){
int[][] a = new int[10][10];
for (int i = 0; i < 10; i++) {
a[i][i] = 1;
a[i][0] = 1;
}
for (int i = 2; i < 10; i++) {
for (int j = 1; j < i; j++) {
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 2 * (10 - i) - 1; k++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
- difficulty : ⭐⭐⭐⭐
- title : print out Yang Hui triangle
- Logic : Yang Hui triangle property: the numbers in each row are symmetrical, starting from 1 and gradually increasing, then decreasing, returning to 1. The number of digits in the nth row is n. The sum of the numbers in the nth row is 2^(n-1). Each number is equal to the sum of the left and right numbers in the previous line. This property can be used to write the entire Yang Hui triangle. The first number in the nth row is 1, the second number is 1×(n-1), the third number is 1×(n-1)×(n-2)/2, and the fourth number is 1×(n-1)×(n-2)/2×(n-3)/3...and so on.
- extension : Yang Hui's triangle is a geometric arrangement of binomial coefficients in the triangle, which appeared in the book "Detailed Explanation of Nine Chapter Algorithms" written by Yang Hui, a mathematician in the Southern Song Dynasty of China in 1261. In Europe, Pascal (1623-1662) discovered this law in 1654, so this table is also called Pascal's triangle. Pascal’s discovery was 393 years later than Yang Hui and 600 years later than Jia Xian.
6. Find the greatest common divisor and the least common multiple
@Test
public void test_Prime() {
int a = 10, b = 24;
int m = division(a, b);
int n = a * b / m;
System.out.println("最大公约数: " + m);
System.out.println("最小公倍数: " + n);
}
public int division(int x, int y) {
int t;
if (x < y) {
t = x;
x = y;
y = t;
}
while (y != 0) {
if (x == y)
return 1;
else {
int k = x % y;
x = y;
y = k;
}
}
return x;
}
- difficulty : ⭐⭐⭐
- title : two positive integers m and n, find their greatest common divisor and least common multiple.
- logic : In the loop, as long as the divisor is not equal to 0, divide the larger number by the smaller number, and use the smaller number as the larger number in the next round, and the remainder as the smaller one in the next round. The number of, so loop until the value of the smaller number is 0, return the larger number, this number is the least common divisor, the least common multiple is the product of the two numbers divided by the least common multiple.
- extension : the greatest common divisor, also known as the greatest common divisor, the greatest common divisor, refers to the largest divisor of two or more integers. The greatest common divisor of a, b is denoted as (a, b). Similarly, the greatest common divisor of a, b, c is denoted as (a, b, c), and the greatest common divisor of multiple integers also has the same sign. There are many ways to find the greatest common divisor, the common ones are prime factorization, short division, toss and turn, and more subtraction. The concept corresponding to the greatest common divisor is the least common multiple, and the least common multiple of a, b is recorded as [a, b]. The common multiple of two or more integers is called their common multiple, and the smallest common multiple except 0 is called the least common multiple of these integers. The least common multiple of an integer a, b is recorded as [a, b]. Similarly, the least common multiple of a, b, c is recorded as [a, b, c], and the least common multiple of multiple integers has the same sign.
7. Perfect square number
@Test
public void test_PerfectSquare() {
for (long l = 1L; l < 100000; l++) {
if (Math.sqrt((l + 100)) % 1 == 0) {
if (Math.sqrt((l + 268)) % 1 == 0) {
System.out.println(l + "加100是一个完全平方数,再加168又是一个完全平方数");
}
}
}
}
- difficulty : ⭐⭐⭐⭐
- title : an integer, after adding 100 to a perfect square number, and adding 168 to a perfect square number, what is the number?
- logic : judge within 100,000, first add 100 to the number and then open the square, then add 268 to the number and then open the square. If the result after the square meets the following conditions, it is the result.
- extended : perfect square refers to multiplying oneself by an integer such as 1, 2 2, 3*3, etc., and so on. If a number can be expressed in the form of the square of a certain integer, then the number is called a perfect square number. A perfect square number is a non-negative number, and a perfect square number has two terms. Be careful not to be confused with the completely flat method.
8. Find the sum of the main diagonals
@Test
public void test_Sum() {
Scanner s = new Scanner(System.in);
int[][] a = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = s.nextInt();
}
}
System.out.println("输入的3 * 3 矩阵是:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
sum += a[i][j];
}
}
}
System.out.println("对角线和是 " + sum);
}
- difficulty : ⭐⭐⭐
- Topic : Find the sum of the diagonal elements of a 3*3 matrix
- logic : Use double for loop control to input a two-dimensional array, and then accumulate ai to output.
- extension : In an n-order square matrix (or n-order determinant), the diagonal line of n elements in the diagonal direction from the upper left corner to the lower right corner is called the n-order square matrix (or row and column). Formula) of the main diagonal.
9. Solve the final number
@Test
public void test_solution() {
System.out.println("1到1000的完数有: ");
for (int i = 1; i < 1000; i++) {
int t = 0;
for (int j = 1; j <= i / 2; j++) {
if (i % j == 0) {
t = t + j;
}
}
if (t == i) {
System.out.print(i + " ");
}
}
}
- difficulty : ⭐⭐⭐⭐
- title : If a number is exactly equal to the sum of its factors, this number is called the "complete number". For example, 6=1+2+3. Programming to find all the numbers within 1000
- logic : If p is a prime number and 2^p-1 is also a prime number, then (2^p-1)X2^(p-1) is a perfect number.
- extends : Perfect numbers, also known as perfect numbers or perfect numbers, are some special natural numbers. The sum (ie factor function) of all its true factors (ie divisors other than itself) is exactly equal to itself.
10. Find the value of s=a+aa+aaa+aaaa+aa...a
@Test
public void test_asum() {
long a = 2, b = 0;
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i = 0;
long sum = 0;
while (i < n) {
b = b + a;
sum = sum + b;
a = a * 10;
++i;
}
System.out.println("input number: " + n);
System.out.println(sum);
}
- Difficulty : ⭐⭐⭐
- title : find the value of s=a+aa+aaa+aaaa+aa...a, where a is a number. For example, 2+22+222+2222+22222 (at this time, 5 numbers are added together), and the addition of several numbers is controlled by the keyboard.
- logic : define a variable b, and assign the initial value to 0; define a variable sum, and assign the initial value to 0. After entering the loop, assign the value of a + b to b, and assign the value of sum + b to sum; At the same time, increase a ten times, ++ i; continue the loop; after the loop ends, output the value of sum.
11. No repeated three digits
@Test
public void test_AC() {
int count = 0;
for (int x = 1; x < 5; x++) {
for (int y = 1; y < 5; y++) {
for (int z = 1; z < 5; z++) {
if (x != y && y != z && x != z) {
count++;
System.out.print(x * 100 + y * 10 + z + " ");
if (count % 4 == 0) {
System.out.println();
}
}
}
}
}
System.out.println("共有" + count + "个三位数");
}
- Difficulty : ⭐⭐⭐⭐
- Topic : There are 1, 2, 3, and 4 numbers. How many different three-digit numbers can be formed without repeated numbers? How many are they?
- Logic : The numbers that can be filled in the hundreds, tens, and ones are all 1, 2, 3, and 4. After composing all the permutations, remove the permutations that do not meet the conditions.
12. Output sequence from small to large
public class SmallToBig {
public static void main(String[] args) {
SmallToBig fnc = new SmallToBig();
int a, b, c;
System.out.println("Input 3 numbers:");
a = fnc.input();
b = fnc.input();
c = fnc.input();
if (a > b) {
int t = a;
a = b;
b = t;
}
if (a > c) {
int t = a;
a = c;
c = t;
}
if (b > c) {
int t = b;
b = c;
c = t;
}
System.out.println(a + " " + b + " " + c);
}
public int input() {
int value = 0;
Scanner s = new Scanner(System.in);
value = s.nextInt();
return value;
}
public void compare(int x, int y) {// 此方法没用
if (x > y) {
int t = x;
x = y;
y = t;
}
}
}
- difficulty : ⭐⭐
- title : input three integers x, y, z, please output these three numbers from small to large
- logic : The way to put the smallest number on x, first compare x with y, if x> y, exchange the values of x and y, and then compare x with z, if x> z then Exchange the values of x and z so that x can be minimized.
13. Monkey eating peach problem
public class Monkey {
public static void main(String[] args) {
int lastdayNum = 1;
for (int i = 2; i <= 10; i++) {
lastdayNum = (lastdayNum + 1) * 2;
}
System.out.println("猴子第一天摘了 " + lastdayNum + " 个桃子");
}
}
- difficulty : ⭐⭐⭐⭐
- Topic : The monkey picked off a few peaches on the first day, and ate half of it immediately, but it was not addictive. He ate one more and ate half of the remaining peaches the next morning and ate one more peach. After that, every morning I ate half and one of the remaining half of the previous day. When I wanted to eat again in the morning of the 10th day, I saw that there was only one peach left. How many were picked on the first day.
- Logic : Adopt the method of reverse thinking, inferring from the back to the front.
14. Table Tennis Competition
public class Compete {
static char[] m = { 'a', 'b', 'c' };
static char[] n = { 'x', 'y', 'z' };
public static void main(String[] args) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < n.length; j++) {
if (m[i] == 'a' && n[j] == 'x') {
continue;
} else if (m[i] == 'a' && n[j] == 'y') {
continue;
} else if ((m[i] == 'c' && n[j] == 'x')
|| (m[i] == 'c' && n[j] == 'z')) {
continue;
} else if ((m[i] == 'b' && n[j] == 'z')
|| (m[i] == 'b' && n[j] == 'y')) {
continue;
} else
System.out.println(m[i] + " vs " + n[j]);
}
}
}
}
- Difficulty : ⭐⭐⭐⭐
- Topic : Two table tennis teams compete, each with three players. Team A has three persons a, b, and c, and Team B has three persons x, y, and z. Lots have been drawn to determine the list of matches. Someone asked the players for the roster of the game. a says he does not compare with x, c says he does not compare with x, z, please program to find the list of the three teams.
15. Find the sum of the scores
public class FenShu {
public static void main(String[] args) {
int x = 2, y = 1, t;
double sum = 0;
DecimalFormat df = new DecimalFormat("#0.0000");
for (int i = 1; i <= 20; i++) {
sum += (double) x / y;
t = y;
y = x;
x = y + t;
System.out.println("第 " + i + " 次相加,和是 " + df.format(sum));
}
}
}
- difficulty : ⭐⭐⭐⭐
- ... Find the sum of the first 20 items of this sequence.
- logic : grasp the law of change in the numerator and denominator.
16. Find the sum of factorials
public class JieCheng {
static long sum = 0;
static long fac = 0;
public static void main(String[] args) {
long sum = 0;
long fac = 1;
for (int i = 1; i <= 10; i++) {
fac = fac * i;
sum += fac;
}
System.out.println(sum);
}
}
- Difficulty : ⭐⭐⭐
- title 1+2!+3!+...+20!
- Logic : Turn accumulation into accumulated multiplication
- extension : Factorial is an arithmetic symbol invented by Christian Kramp (1760-1826) in 1808 and is a mathematical term. The factorial of a positive integer is the product of all positive integers less than or equal to this number, and the factorial of 0 is 1. The factorial of a natural number n is written as n!. In 1808, Keston Kaman introduced this notation.
17. Palindrome judgment
public class HuiWen {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("请输入一个正整数:");
long a = s.nextLong();
String ss = Long.toString(a);
char[] ch = ss.toCharArray();
boolean is = true;
int j = ch.length;
for (int i = 0; i < j / 2; i++) {
if (ch[i] != ch[j - i - 1]) {
is = false;
}
}
if (is == true) {
System.out.println("这是一个回文数");
} else {
System.out.println("这不是一个回文数");
}
}
}
- Difficulty : ⭐⭐⭐
- title : a 5-digit number, to determine whether it is a palindrome number. That is, 12321 is the number of palindrome, the ones place is the same as the ten thousand place, and the ten place is the same as the thousand place.
18. Output sequence in sequence
public class ShunXu {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = s.nextInt();
if (a < b) {
int t = a;
a = b;
b = t;
}
if (a < c) {
int t = a;
a = c;
c = t;
}
if (b < c) {
int t = b;
b = c;
c = t;
}
System.out.println("从大到小的顺序输出:");
System.out.println(a + " " + b + " " + c);
}
}
- Difficulty : ⭐⭐⭐
- title : input 3 numbers a, b, c, and output in order of magnitude
19. Position substitution
public class TiHuan {
static final int N = 8;
public static void main(String[] args) {
int[] a = new int[N];
Scanner s = new Scanner(System.in);
int index1 = 0, index2 = 0;
System.out.println("please input numbers");
for (int i = 0; i < N; i++) {
a[i] = s.nextInt();
System.out.print(a[i] + " ");
}
int max = a[0], min = a[0];
for (int i = 0; i < a.length; i++) {
if (a[i] > max) {
max = a[i];
index1 = i;
}
if (a[i] < min) {
min = a[i];
index2 = i;
}
}
if (index1 != 0) {
int temp = a[0];
a[0] = a[index1];
a[index1] = temp;
}
if (index2 != a.length - 1) {
int temp = a[a.length - 1];
a[a.length - 1] = a[index2];
a[index2] = temp;
}
System.out.println("after swop:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
- Difficulty : ⭐⭐
- title : input array, the largest exchange with the first element, the smallest exchange with the last element, output array.
20. Number of 1
long startTime = System.currentTimeMillis();
int num = 10000000, saveNum = 1, countNum = 0, lastNum = 0;
int copyNum = num;
while (num != 0) {
lastNum = num % 10;
num /= 10;
if (lastNum == 0) {
// 如果是0那么正好是少了一次所以num不加1了
countNum += num * saveNum;
} else if (lastNum == 1) {
// 如果是1说明当前数内少了一次所以num不加1,而且当前1所在位置
// 有1的个数,就是去除当前1最高位,剩下位数,的个数。
countNum += num * saveNum + copyNum % saveNum + 1;
} else {
// 如果非1非0.直接用公式计算
// abcd...=(abc+1)*1+(ab+1)*10+(a+1)*100+(1)*1000...
countNum += (num + 1) * saveNum;
}
saveNum *= 10;
}
System.out.println("1的个数:" + countNum);
System.out.println("计算耗时:" + (System.currentTimeMillis() - startTime) + "毫秒");
- Difficulty : ⭐⭐⭐⭐
- title : 1 to n, the number of times 1 appears. For example: 1~10, 1 appears twice.
- logic : We can find that the number of 1s appears in a regular cycle among 100, 1000, and 10000. 11, 12, 13, 14, or 21, 31, 41, 51, and a single 1 appears. Finally, the general formula can be drawn: abcd...=(abc+1) 1+(ab+1) 10+(a+1) 100+(1) 1000..., abcd represents the number of digits. In addition, the implementation process also needs to consider situations such as less than 100, such as 98, 1232, and so on.
Third, deep expansion
The Java code itself is a concrete realization of mathematical logic based on data structures and algorithms, and if you don’t know the mathematical knowledge implicit in the code, you will simply ignore it, and you won’t understand the source code.
Like I asked you:
- Have you proved why HashCode uses 31 as a multiplier?
- What is the function of the disturbance function, and what other scenarios are it used in?
- What is the specific performance of zipper addressing and open addressing, and how to solve the collision problem?
- Do you know that the golden section is used in the implementation of ThreadLocal?
- How do CLH and MCS implement fair locks? What is the code?
- jvmti can be used for non-invasive monitoring of thread pool status, have you used it?
So Xiao Fu compiled a book, "Java Handbook" is a PDF book explaining the core technology of Java with interview questions as the entrance, and the content in the book also to prove to you that the 160a1c726d4c2a code is specific to mathematical logic. To achieve. Why do you say that? When you read the book carefully, you will find that there is a lot of mathematical knowledge here, including: disturbance function, load factor, zipper addressing, open addressing, Fibonacci hashing, and the use of golden section points, etc. Wait.
Java Manual , data download: https://codechina.csdn.net/MiddlewareDesign/doc/-/issues/8
Four, summary
- Programming is one of the most difficult branches of applied mathematics; the poorer mathematicians had better remain pure mathematicians. https://www.cs.utexas.edu/users/EWD/transcriptions/EWD04xx/EWD498.html
- Merely can only write mathematics and cannot write code. Those who can write code but do not understand mathematics can only be CRUD coders. Mathematics knowledge helps you design data structures and implement algorithm logic, and code ability helps you control design patterns and architecture models. The combination and use of multiple aspects of knowledge is the main difference between a code farmer and an engineer, and it is also the key to whether to have core competitiveness.
- Learning knowledge sometimes cannot see how far the road ahead is, but even if it is a mud pit, as long as you keep wriggling, tossing, and rolling, you can catch a loach.
The road to knowledge is the joy of discovering knowledge, and the sense of accomplishment of learning knowledge, which constantly urges you to move forward.
Five, series recommendation
- Summary of study route resources from four years of university to five years of work after graduation
- Two-year work resume written like this, who wants you!
- working for 3 years, what information can I get a monthly salary of 30K?
- programmer published a technical book, what is the experience?
- Sharing and analysis of the small partner
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。