All divisors of a number

In this article, we are going to find all divisors of a number using java code.

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:-

package gangforcode;
import java.util.*;
public class AllDivisors {

	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:-

Java code to find all divisors of given number

We can use the same logic to find all divisors of a given number using other programming languages like C, C++, Python, etc.

Leave a Comment