All Divisors of a Number

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

All Divisors of a Number

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

Leave a Comment