Code analysis of solving perfect number in Java language
1. Concept
First, let's understand what is a perfect number?
Problem Description: if a natural number, the sum of all its true factors (i.e. divisors other than itself) is exactly equal to itself, this number is called perfect number. It is called "perfect number" for short
For example,
6=1+2+3 28=1+2+4+7+14 496=1+2+4+8+16+31+62+124+248 8128=1+2+4+8+16+32+64+127+254+508+1016+2032+4064
According to the definition of perfect number, it is not too difficult to solve the perfect number by program. First solve all the true factors of this number, and then add them to judge whether it is equal to itself. However, when the number is very small, there is no problem. Once the number exceeds a certain value, the problem will come, and the execution efficiency of the program will become low.
When we optimize the algorithm logic of the program, we often consider a problem: how to make efficient use of the characteristics of the computer? Is there a lot of repeated useless work in the algorithm it defines? Considering this problem along this line, we will soon get another solution.
2. Explain
2.1 analysis
Is it easy to think of the factorization we mentioned earlier? Yes, in solving perfect numbers, we will use factorization. Generally speaking, there are three steps to solve the perfect number:
1. Find a certain number of prime tables
2. Use the prime number table to find the factorization of the specified number
3. Use factorization to find the sum of all true factors and check whether it is a perfect number
2.2 difficulties
At first glance, the first and second steps are no problem. We have discussed them in the previous two articles. Students who are not clear can check them.
The focus is on the third step, how to find the truth factor and? The method is very simple. You should first know that adding all the true factors (students who do not know the concept of true factors, go and have a look) and the number itself will be twice the number (some students do not know, should they know it now?). For example:
In fact, this equation can be transformed into: (code input error, I'll use the screenshot)
Did you find it? 2 and 7 are obtained by factorization. So, is there a simplification in the program?
2.3 conclusion
As long as the factorization is obtained, the value behind the equation can be obtained by using the cycle. Dividing the value by 2 is the true factor sum; At the first glance, you may think of using the proportional series formula to solve the equation, but the power operation will be used. When reading the factorization array, you can calculate the value behind the equation at the same time.
3. Code
summary
The above is all about the code analysis of solving perfect numbers in Java language. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message and point out!