经常早上肚子疼是什么原因
Java provides a different kind of number system to the user; the perfect number is also one kind of number system that is provided by java. We can consider any number as a perfect number in Java. If all factors excluding the number it is equal to the given number, then we can consider the given number to be a perfect number. In Java, we can use different ways to find the perfect number. Basically, the perfect number is nothing but any number whose base is 10 in the number system, and it is a subfield of the number system in mathematics. As per user requirements, we can use the perfect number system.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Logic behind Perfect number
Now let’s see the logic behind the perfect number in java as follows.
The basic logic of the perfect number is very simple. First, we need to find out the positive factor of a given number then make a sum of all factors excluding the number itself. If the sum of the factor is equal to the given number, then we can say that the given number is the perfect number, and if the sum of the factor is not equal to the given number, then we can say that the given number is not a perfect number. Let’s see an example of a perfect number; then we will get a detailed idea as follows.
Suppose we need to check if 8 is a perfect number or not.
- First find out the positive factor that is 1, 2, 4, and 8. Now make the addition of all factors excluding the 8, and we get the result is 7. Now compare the result with the given number; see here both numbers are different. That means we can say that this number is not a perfect number.
- Now let’s consider another number: 6.
- Find the positive factor of 6 is that 1, 2, 3, and 6.
- The Sum of all factors is 6, excluding 6.
- Now compare the result with the given number, see here the given number and result is the same that means we can say that the given number is a perfect number.
How to Check Perfect number in Java?
Now let’s see how to check the perfect number java as follows. In java programming, there are three different ways to check the perfect number as follows.
1.? By using while loop
In the while loop, we need to follow some steps as follows.
1. First, we need to read the number entered from the user.
2. The loop will continue until the condition (j<=no/2) is false. If the remainder of no/j is 0, then add the value of j into the sum and increase the value of j. After completion of all iterations, compare the result. If the booth number is equal, then print the given number as a perfect number; else, print the given number as not a perfect number.
3. For example no=8, j=1 no/2=4, so j <=4 means condition is true, now find the factor.
8%j=0 true then sum =1
J=2 2<4 is true 8%2 =0 is true and sum= 1+3=3.
So in this way, we complete all the iterations to find the perfect number.
2. By using Static Method
In this method, we can call a static method to check the perfect number; in this method, we just need to call the PerfacOrNot method. It automatically calculates the sum of all positive factors and checks if the given number is perfect or not.
3. By using the recursion Method
In this method, we also call the PerfectOrNot () method using objects. In this method, execution starts itself and calls PerfectOrNot (). It repeats the iteration until the j<= number/2 is false.
Examples
Now let’s see the different examples of perfect numbers in Java as follows.
Example #1
Code:
import java.util.Scanner; class Perfect_number1 { public static void main(String arg[]) { long num,s=0; Scanner s_c=new Scanner(System.in); System.out.println("Enter number"); num=s_c.nextLong(); int j=1; while(j<=num/2) { if(num%j==0) { s+=j; } j++; } if(s==num) { System.out.println(num+" the given number is perfect number"); } else System.out.println(num+" the given number is not perfect number"); } }
Explanation
By using the above program, we try to implement perfect numbers in java with a while loop. The coding of the above program is very simple here we created the main method; inside the main method, we use scanner class and while loop to find a factor of a given number and add that factor into the s variable that is the sum of the factor as shown in the above program. Finally, we compare both numbers and print the message as per the comparison. The final output of the above program we illustrate by using the following screenshot as follows.
Example #2
Now let’s see another example of a perfect number by using the static method as follows.
Code:
import java.util.Scanner; class Perfect_Method { public static void main(String arg[]) { long num,m; Scanner s_c=new Scanner(System.in); System.out.println("Enter number"); num=s_c.nextLong(); m=perfectOrNot(num); if(m==num) System.out.println(num+" The given number is perfect number"); else System.out.println(num+" The given number is not perfect number"); } static long perfectOrNot(long n) { long s=0; for(int j=1;j<=n/2;j++) { if(n%j==0) { s+=j; } } return s; } }
Explanation
In the above program, we use a static method to check if a given number is a perfect number or not. In the above program, we use the perfecOrNot () method. After that, we use a for loop to find the factors of the given number, and the remaining process is the same, that is, to compare the result with the given number and print a message according to the comparison. The final output of the above program we illustrate by using the following screenshot as follows.
Example #3
Now let’s see another example to check perfect numbers by using the recursive Method as follows.
Code:
public class Recursive { static int n = 200; static int s = 0; static int d = 1; static int findPerfect(int n, int d) { { if(d<=n/2) { if(n%d==0) { s+=d; } d++; findPerfect(n,d); } return s; } } public static void main(String args[]) { int r = findPerfect(n,d); if(r == n) System.out.println(" The given number is perfect Number"); else System.out.println("The given number is not perfect Number"); } }
Explanation
In the above program, we are using a recursive method to check the perfect number. The final output of the above program we illustrate by using the following screenshot as follows.
Conclusion
We hope from this article you learn Perfect Number in java. From the above article, we have learned the basic logic of Perfect Numbers, and we also see different examples of Perfect Numbers. From this article, we learned how and when we use the Perfect Number in java.
The above is the detailed content of Perfect Number in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

Full screen layout can be achieved using Flexbox or Grid. The core is to make the minimum height of the page the viewport height (min-height:100vh); 2. Use flex:1 or grid-template-rows:auto1frauto to make the content area occupy the remaining space; 3. Set box-sizing:border-box to ensure that the margin does not exceed the container; 4. Optimize the mobile experience with responsive media query; this solution is compatible with good structure and is suitable for login pages, dashboards and other scenarios, and finally realizes a full screen page layout with vertical centering and full viewport.

Selecting the Java SpringBoot React technology stack can build stable and efficient full-stack web applications, suitable for small and medium-sized to large enterprise-level systems. 2. The backend uses SpringBoot to quickly build RESTfulAPI. The core components include SpringWeb, SpringDataJPA, SpringSecurity, Lombok and Swagger. The front-end separation is achieved through @RestController returning JSON data. 3. The front-end uses React (in conjunction with Vite or CreateReactApp) to develop a responsive interface, uses Axios to call the back-end API, and ReactRouter

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.
