Algorithm
1. Start
2. Initialize a variable 'num' with the given number for which factors need to be displayed.
3. Print "Factors of " + num + " are: "
4. Loop from i = 1 to i <= num
a. If num % i == 0
i. Print i
5. End
Code Examples
#1 Code Example- Factors of a Positive Integer
Code -
Java Programming
public class Main {
public static void main(String[] args) {
// positive number
int number = 60;
System.out.print("Factors of " + number + " are: ");
// loop runs from 1 to 60
for (int i = 1; i < = number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}
Copy The Code &
Try With Live Editor
Output
Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60
#2 Code Example- Factors of Negative Number
Code -
Java Programming
class Main {
public static void main(String[] args) {
// negative number
int number = -60;
System.out.print("Factors of " + number + " are: ");
// run loop from -60 to 60
for(int i = number; i < = Math.abs(number); ++i) {
// skips the iteration for i = 0
if(i == 0) {
continue;
}
else {
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}
}
Copy The Code &
Try With Live Editor
Output
Factors of -60 are: -60 -30 -20 -15 -12 -10 -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 10 12 15 20 30 60
Demonstration
Java Programing Example to Display Factors of a Number-DEvsEnv