Page 291 - CA_Blue( J )_Class9
P. 291
VARIABLE DESCRIPTION
NAME DATATYPE DESCRIPTION
n int Accept a number
i int Loop Variable
sum int Sum of the series
Program 14 Write a program to input a number and print all the perfect numbers up to it.
1 import java.util.*; //importing “util”package
2 class perfect //class name
3 {
4 public static void main()
5 {
6 Scanner sc= new Scanner(System.in);
7 int n,i,s,j; //Declaration of variable
8 System.out.print("Enter a number : ");
9 n=sc.nextInt(); //Accepting last value
10 System.out.print("The perfect numbers from 1 to "+n+" : ");
11 for(i=1;i<=n;i++) //Loop Variable
12 {
13 s=0;
14 for(j=1;j<i;j++) //Loop to check perfect number
15 {
16 if(i%j==0)
17 {
18 s=s+j; //Sum of the factors
19 }
20 }
21 if(s==i) //Checking of perfect number
22 System.out.print(i +" "); //Displaying the perfect numbers
23 }
24 }
25 }
You will get the following output:
Enter a number : 10000
The perfect numbers from 1 to 10000 : 6 28 496 8128
Internal Assessment 289

