Write a program to print all the perfect nos between two limit enterd by the user with help of the following function
boolean IsPerfect(int num) - to return true if num is perfect otherwise print false.
A Number is said to be perfect if sum of all factors excluding itself should be equal to the number. Let N=6, Its factors are 1,2,3 and the sum of the factors (1+2+3)=6. So 6 is the perfect no. Examples of some Other perfect numbers are 28 and 496.
void showPerfectNumbers(int start,int end) - to print all the perfect nos between start and end limits by using functions IsPerfect().
Write a main function to execute the same.
import java.util.*; public class PerfectNumbers { public boolean IsPerfect(int num) { int sum=0; for(int k=1;k<= num/2;k++) { if(num%k==0) { sum=sum+k; } } if(sum==num) { return true; } else { return false; } } public void showPerfectNumbers(int start, int end) { System.out.println("Perfect Numbers are \n================"); for(int i=start;i<=end;i++) { if(IsPerfect(i)) { System.out.println(i); } } } public static void main(String []args) { Scanner sc=new Scanner(System.in); System.out.print("Enter Start Number:"); int s=sc.nextInt(); System.out.print("Enter end Number:"); int e=sc.nextInt(); PerfectNumbers pn=new PerfectNumbers(); pn.showPerfectNumbers(s,e); } }
Enter Start Number:2
Enter end Number:900
Perfect Numbers are
================
6
28
496