AtCoder beginner Contets C - Reconciled? Difficulty: 647
This theme, factorial
Ruby
It is the factorial of the dog N
and the factorial of the monkey M
.
If you make the factorial a function, you can use it for later contests.
ruby.rb
n, m = gets.split.map(&:to_i)
MOD = 1_000_000_007
def nPk(n, k)
r = 1
while k > 0
r *= n
r %= MOD
n -= 1
k -= 1
end
r
end
if (n - m).abs > 1
puts 0
elsif n == m
puts nPk(n, n) * nPk(m, m) * 2 % MOD
else
puts nPk(n, n) * nPk(m, m) % MOD
end
nCk.rb
def nCk(n, k)
r, j = 1, 1
return 0 if k > n || k < 0
k = n - k if n - k < k
while j <= k
r *= n
n -= 1
r /= j
j += 1
end
r
end
This is also reusable ~~ copy ~~. Python
python.py
n, m = map(int, input().split())
MOD = 1000000007
def nPk(n, k):
r = 1
while k > 0:
r *= n
r %= MOD
n -= 1
k -= 1
return r
if abs(n - m) > 1:
print(0)
elif n == m:
print(nPk(n, n) * nPk(m, m) * 2 % MOD)
else:
print(nPk(n, n) * nPk(m, m) % MOD)
Perl
perl.pl
chomp (my ($n, $m) = split / /, <STDIN>);
my $MOD = 1_000_000_007;
sub nPk {
my ($n, $k) = @_;
my $r = 1;
while ($k) {
$r *= $n;
$r %= $MOD;
$n -= 1;
$k -= 1;
}
$r;
}
if (abs($n - $m) > 1) {
print "0\n";
} elsif ($n == $m) {
print (nPk($n, $n) * nPk($m, $m) * 2 % $MOD), "\n";
} else {
print (nPk($n, $n) * nPk($m, $m) % $MOD), "\n";
}
nCk.pl
sub nCk {
my ($n, $k) = @_;
my ($r, $j) = (1, 1);
return 0 if $k > $n || $k < 0;
$k = ($n - $k) if ($n - $k) < $k;
while ($j <= $k) {
$r *= $n--;
$r /= $j++;
}
$r;
}
Java
java.java
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
int m = Integer.parseInt(sc.next());
sc.close();
int MOD = 1_000_000_007;
if (Math.abs(n - m) > 1) {
System.out.println(0);
} else if (n == m) {
System.out.println((((nPk(n, n, MOD) * nPk(m, m, MOD)) % MOD) * 2) % MOD);
} else {
System.out.println((nPk(n, n, MOD) * nPk(m, m, MOD)) % MOD);
}
}
static long nPk(int n, int k, int MOD) {
long r = 1;
while (k > 0) {
r *= n;
r %= MOD;
n -= 1;
k -= 1;
}
return r;
}
}
Ruby | Python | Perl | Java | |
---|---|---|---|---|
Code length | 287 Byte | 314 Byte | 386 Byte | 794 Byte |
Execution time | 21 ms | 64 ms | 41 ms | 111 ms |
memory | 1788 KB | 3064 KB | 384 KB | 23764 KB |
Recommended Posts