If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To find all the divisors of a given number in Java, you can use a loop to check for factors of the number. A divisor of a number is an integer that divides the given number without leaving a remainder. Here's a Java program to find all the divisors of a given number:
javaCopy code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Divisors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();
List<Integer> divisors = findDivisors(number);
System.out.println("Divisors of " + number + " are: " + divisors);
scanner.close();
}
// Function to find all divisors of a given number
public static List<Integer> findDivisors(int number) {
List<Integer> divisors = new ArrayList<>();
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
divisors.add(i);
}
}
return divisors;
}
}
Example output:
lessCopy code
Enter a positive integer: 24
Divisors of 24 are: [1, 2, 3, 4, 6, 8, 12, 24]
In the program above, we take the user input for the number and store it in the variable number
. We call the findDivisors
function to find all the divisors of the number. The findDivisors
function iterates from 1 to number
, and for each value of i
, it checks if number
is divisible by i
without leaving a remainder. If it is, i
is a divisor, and we add it to the list of divisors.
The program then prints the list of divisors to the console.
Keep in mind that the divisors are returned as a list of integers. You can modify the program to display the divisors in a different format or use the divisors for further calculations if needed.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform