给定整数n,在n中找到给定质数(r)的幂!
例子 :
Input : n = 6 r = 3
Factorial of 6 is 720 = 2^4 * 3^2 *5 (prime factor 2,3,5)
and power of 3 is 2
Output : 2
Input : n = 2000 r = 7
Output : 330
一种简单的方法是首先计算n的阶乘,然后将其分解以找到质数的幂。
由于数字的阶乘是一个大数字,因此上述方法可能会导致稍大的数字发生溢出。这个想法是考虑阶乘n的素因子。
n的Legendre分解!
对于任何质数p和任何整数n,令Vp(n)是除以n的p的最大幂(即n的p-adic估值)的指数。然后
Vp(n)=楼板面积(n / p ^ i)的总和,我从1到无穷大
虽然右边的公式是一个无限大的和,但对于n和p的任何特定值,它仅具有有限的许多非零项:对于每个i足够大以使p ^ i> n的人,其底数为(n / p ^ i) = 0。因为,总和是收敛的。
Power of ‘r’ in n! = floor(n/r) + floor(n/r^2) + floor(n/r^3) + ....
程序计算一个数字的力量。 r在n!根据上述公式。
C++
// C++ program to find power of
// a prime number ‘r’ in n!
#include
using namespace std;
// Function to return power of a
// no. 'r' in factorial of n
int power(int n, int r)
{
// Keep dividing n by powers of
// 'r' and update count
int count = 0;
for (int i = r; (n / i) >= 1; i = i * r)
count += n / i;
return count;
}
// Driver program to
// test above function
int main()
{
int n = 6, r = 3;
printf(" %d ", power(n, r));
return 0;
}
Java
// Java program to find power of
// a prime number 'r' in n!
class GFG {
// Function to return power of a
// no. 'r' in factorial of n
static int power(int n, int r) {
// Keep dividing n by powers of
// 'r' and update count
int count = 0;
for (int i = r; (n / i) >= 1; i = i * r)
count += n / i;
return count;
}
// Driver code
public static void main(String[] args)
{
int n = 6, r = 3;
System.out.print(power(n, r));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to find power
# of a prime number ‘r’ in n!
# Function to return power of a
# no. 'r' in factorial of n
def power(n, r):
# Keep dividing n by powers of
# 'r' and update count
count = 0; i = r
while((n / i) >= 1):
count += n / i
i = i * r
return int(count)
# Driver Code
n = 6; r = 3
print(power(n, r))
# This code is contributed by Smitha Dinesh Semwal.
C#
// C# program to find power of
// a prime number 'r' in n!
using System;
class GFG {
// Function to return power of a
// no. 'r' in factorial of n
static int power(int n, int r) {
// Keep dividing n by powers of
// 'r' and update count
int count = 0;
for (int i = r; (n / i) >= 1; i = i * r)
count += n / i;
return count;
}
// Driver code
public static void Main()
{
int n = 6, r = 3;
Console.WriteLine(power(n, r));
}
}
// This code is contributed by vt_m.
PHP
= 1;
$i = $i * $r)
$count += $n / $i;
return $count;
}
// Driver Code
$n = 6; $r = 3;
echo power($n, $r);
// This code is contributed by ajit
?>
Javascript
输出:
2