当给出值 n 和 r 时,Java 程序查找排列
排列是指可以按某种方式排列或排序集合成员的方式。从 n 个元素中排列 k 个元素的排列公式为——
nPk = n! / (n - k)!
算法
1. Define values for n and r. 2. Calculate factorial of n and (n-r). 3. Divide factorial(n) by factorial(n-r). 4. Display result as a permutation.
示例
import java.util.Scanner;
public class Permutation {
static int factorial(int n) {
int f;
for(f = 1; n > 1; n--){
f *= n;
}
return f;
}
static int npr(int n,int r) {
return factorial(n)/factorial(n-r);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n :");
int n = sc.nextInt();
System.out.println("Enter the value of r :");
int r = sc.nextInt();
System.out.println("npr value is ::"+npr(n,r));
}
}输出
Enter the value of n : 4 Enter the value of r : 3 npr value is ::24
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP