Java Online Compiler
Example: Permutations of n people in r seats in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Permutations of n people in r seats import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Method to calculate factorial of a number public static long factorial(int num) { if (num < 0) { return 0; // Factorial not defined for negative numbers } long result = 1; for (int i = 1; i <= num; i++) { result *= i; } return result; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get input for n (number of people) System.out.print("Enter the total number of people (n): "); int n = scanner.nextInt(); // Step 2: Get input for r (number of seats) System.out.print("Enter the number of seats available (r): "); int r = scanner.nextInt(); // Step 3: Validate inputs if (n < 0 || r < 0) { System.out.println("Number of people and seats cannot be negative."); } else if (r > n) { System.out.println("Number of seats cannot be greater than the number of people."); } else { // Step 4: Calculate n! long nFactorial = factorial(n); // Step 5: Calculate (n-r)! long nMinusRFactorial = factorial(n - r); // Step 6: Calculate permutations P(n, r) = n! / (n-r)! long permutations = nFactorial / nMinusRFactorial; // Step 7: Display the result System.out.println("The number of permutations for " + n + " people in " + r + " seats is: " + permutations); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS