In: Computer Science
Problem 1:
More than 2500 years ago, mathematicians got interested in numbers.
Armstrong Numbers: The number 153 has the odd property that 13+53 + 33 = 1 + 125 + 27 = 153. Namely, 153 is equal to the sum of the cubes of its own digits.
Perfect Numbers: A number is said to be perfect if it is the sum of its own divisors (excluding itself). For example, 6 is perfect since 1, 2, and 3 divide evenly into 6 and 1+ 2 + 3 = 6.
Input File
The input is taken from a file named number.in and which a sequence of numbers, one per line, terminated by a line containing the number 0.
Output File
All the numbers read from the input file, are printed one per line followed by a sentence indicating whether the number is or is not Armstrong number and whether it is or is not a perfect number. Sample Input 153 6 0 Sample Output 153 is an Armstrong number but it is not a perfect number. 6 is not an Armstrong number but it is a perfect number.
Note: the program must be write in java
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class NumbersPro {
public static void main(String[] args) throws
Exception {
Scanner sc = new Scanner(new
File("numbers.in"));
PrintWriter pw = new
PrintWriter(new File("output.txt"));
int num;
String out = "";
boolean isAmstrong,
isPerfect;
while (sc.hasNext()) {
out = "";
num =
sc.nextInt();
if (num ==
0)
break;
isAmstrong =
isAmstrong(num);
if
(isAmstrong)
out = num + " is an Armstrong number";
else
out = num + " is not an Armstrong number";
isPerfect =
isPerfect(num);
if
(isPerfect)
out += " and is an Perfect number";
else
out += " but not an perfect number";
pw.println(out);
}
pw.close();
}
private static boolean isPerfect(int number)
{
int sum = 0, i;
for (i = 1; i < number; i++)
{
if (number % i
== 0) {
sum = sum + i;
}
}
return sum == number;
}
private static boolean isAmstrong(int number)
{
int originalNumber = number;
int result = 0;
while (originalNumber != 0) {
int remainder =
originalNumber % 10;
result +=
Math.pow(remainder, 3);
originalNumber
/= 10;
}
return result == number;
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me