Example:-
if number=8 ,then the output will be 1,2,4,8.
Steps:-
- Take the input from the user using a scanner.
- Take an integer i=1.
- Run a loop while(i<=n).
- Inside the while loop check if n is divisible by i, then i is a divisor of n.
- increment i by 1.
- end of the loop.
Java Code to Find All Divisors of Given Number:-
import java.util.*;
public class AllDivisior {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.println("Enter the number");
int n=sc.nextInt();
int i=1;
while(i<=n) {
if(n%i==0) {
System.out.print(i+" ");
}
i++;
}
}
}
Output:-
We can use the same logic to find all divisors of a given number using other programming languages like C, C++, Python, etc.
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java