Computer Science, asked by CopyThat, 4 months ago

Need a JAVA program :
⇒ Write a program to print all Perfect numbers between 1 to 100
⇒ (A number which is equal to the sum of its factors is said to be a Perfect number)
⇒ Ex: Consider the number 6. Its factors are 1,2 and 3, so 1+2+3=6

Answers

Answered by BrainlyProgrammer
16

Correct definition of Perfect Number:-

  • A number is said to be a perfect number when it is equal to the sum of its factors excluding the number itself.
  • Example: 6 ⟹ 1+2+3 => 6 [Note: Here 6 is also a factor but it's excluded according to defination of perfect number]

//Java program to print all the perfect number between 1 to 100

package Programmer;

public class Perfect {

public static void main(String[] args) {

int s;

for(int i=1;i<=100;i++){

s=0;

for(int j=1;j<i;j++){

s=(i%j==0)?(s+j):(s+0);

}

if(s==i)

System.out.println("Perfect number:"+i);

}

}

}

_______

Variable Description:-

  • s:- to calculate the sum
  • I:- to run a loop from 1 to 100
  • j:- to find all the perfect numbers

_______

Explaination:-

  • The program runs I loop from 1 to 100
  • Each iteration, it will intiallize s=0 and run one more loop from 1 to (i-1) [Note the '<' sign between j and I in the second loop]
  • s=(i%j==0)?(s+j):(s+0) This is a ternary statement. Here for your convenience you can also write:

if(i%j==0)

s+=j;

  • In this ternary statement, the control (compiler) will checks the condition and if true assigns the first statement to 's' (statement before ':' symbol) otherwise second statement to 's' (after ':' symbol)
  • j loop terminates soon when the j loop value is >= i
  • now here it will check one more condition (s==I) if true, number is a perfect number!
  • And this happens for all the iterations i.e. from 1 to 100

______

•Output Attached.

Attachments:
Answered by TheBestWriter
2

Need a JAVA program :

⇒ Write a program to print all Perfect numbers between 1 to 100

⇒ (A number which is equal to the sum of its factors is said to be a Perfect number)

⇒ Ex: Consider the number 6. Its factors are 1,2 and 3, so 1+2+3=6

Ânswer

message

Similar questions