forked from Twiggecode/Integer-Sequences
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDerangements.java
39 lines (32 loc) · 882 Bytes
/
Derangements.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.io.*;
import java.util.*;
class Main {
// Function to count derangements
static int countDer(int n) {
// Base case
if(n == 1 || n == 2) {
return n-1;
}
// Variable for storing prev values
int a = 0;
int b = 1;
// manner using above recursive formula
for (int i = 3; i <= n; ++i) {
int cur = (i-1)*(a+b);
a = b;
b = cur;
}
// Return result for n
return b;
}
// Driver Code
public static void main (String[] args)
{
int n ;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
System.out.println("Count of Dearrangements is " +
countDer(n));
}
// Code contributed by skagnihotri
}