Start Practicing LeetCode with Programming Chaska. I have explained my approach to the problems in simple way. I have also shared the optimized code so that you can learn some new.
Perfect number Program in C | C++ | JAVA
Perfect Number: A natural number that is equal to the sum of its all factors (excluding number as its factor itself), is called a Perfect Number.
For Example: Number --> 6factors of 6 are -> 1,2 and 3->1 + 2 + 3 = 6.So, 6 is a Perfect Number.Some of the Perfect numbers are 28, 496, and 8128.
Algorithm to check whether a given number is a Perfect number or not:
Step 1: Accept a number.
Step 2: Find factors of number starting from 1 to number (Do not include the number itself as a factor). If given number is divisible by number smaller than itself, then its a factor.
Step 3: Add all the factors of a number and store it in a variable.
Step 4: If the sum of all the factors of a number is equal to the number itself then Display Perfect number else Display Not a Perfect number.
Step 5: Stop
Implementation in C:
Code 1: This is the general code in C with time complexity of O(n).
Implementation in C++:
Code 2: This is the general code in C++ with time complexity of O(n).
Implementation in JAVA:
Code 3: This is the general code in JAVA with time complexity of O(n).
Start Practicing LeetCode with Programming Chaska. I have explained my approach to the problems in simple way. I have also shared the optimized code so that you can learn some new.
Optimized Code in C | C++ | JAVA:
Code 4: This is optimized code to check perfect numbers. Here we are using mathematical property for factor checking. The factors of a number starting repeating when we go beyond its square root.
Example:
Factors of 6 :
6 = 1 * 6
6 = 2 * 3
------------ (crossed square root of 6)
6 = 3 * 2
6 = 6 * 1
We can see that 2*3 is same as 3*2, so we will not go beyond square root.
Time complexity - O(sqrt(n))
Start Practicing LeetCode with Programming Chaska. I have explained my approach to the problems in simple way. I have also shared the optimized code so that you can learn some new.
0 Comments