Light OJ 1045 Digits of Factorial(求位数)

本文详细介绍了如何解决在特定基础上计算阶乘位数的问题,通过使用对数方法进行高效计算,并提供了关键代码实现。深入探讨了阶乘在不同基数下的变化规律及其在编程中的实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1045 - Digits of Factorial
Time Limit: 2 second(s)Memory Limit: 32 MB

Factorial of an integer is defined by the following function

f(0) = 1

f(n) = f(n - 1) * n, if(n > 0)

So, factorial of 5 is 120. But in different bases, the factorial may be different. For example, factorial of 5 in base 8 is 170.

In this problem, you have to find the number of digit(s) of the factorial of an integer in a certain base.

Input

Input starts with an integer T (≤ 50000), denoting the number of test cases.

Each case begins with two integers n (0 ≤ n ≤ 106) and base (2 ≤ base ≤ 1000). Both of these integers will be given in decimal.

Output

For each case of input you have to print the case number and the digit(s) of factorial n in the given base.

Sample Input

Output for Sample Input

5

5 10

8 10

22 3

1000000 2

0 100

Case 1: 3

Case 2: 5

Case 3: 45

Case 4: 18488885

Case 5: 1

 



也是利用对数来求位数。

代码:
#include<stdio.h>
#include<cmath>
using namespace std;
double a[1000010];
int main()
{
  freopen("in.txt","r",stdin);
  a[1]=log(1);
  for(int i=2;i<=1000000;i++)a[i]=a[i-1]+log(i);
  int t;
  scanf("%d",&t);
  for(int ca=1;ca<=t;ca++)
  {
    int n,b;
    scanf("%d%d",&n,&b);
    if(n==0)
    {
      printf("Case %d: %d\n",ca,1);
      continue;
    }
    double ans=0;
    printf("Case %d: %.0lf\n",ca,floor(a[n]/log(b*1.0))+1);
  }
  return 0;
}


### 计算小数点后数字的位数 要解决这个问题,可以通过模拟手动计算除法的过程来获取小数部分并统计其位数。以下是具体的实现方法: #### 方法描述 程序的核心思路是对两个整数 `a` 和 `b` 进行除法运算,并逐步记录商的小数部分直到满足特定条件为止。在此过程中,我们需要特别注意以下几点: - 如果被除数小于除数,则需要向低位借位继续计算。 - 需要设置一个计数器变量用于跟踪当前已经产生的小数位数量。 下面是一个完整的 C 实现方案[^2]: ```c #include <stdio.h> int main() { int a, b; scanf("%d %d", &a, &b); if (b == 0) { printf("Error: Division by zero.\n"); return 1; } // 初始化变量 int count = 0; // 统计小数位数 int remainder = a % b; // 当余数不为零时持续计算 while (remainder != 0 && count < 3000) { // 设置最大迭代次数防止无限循环 remainder *= 10; int digit = remainder / b; remainder %= b; count++; } printf("The number of decimal places is: %d\n", count); return 0; } ``` 此代码片段实现了对给定两整数执行精确到一定精度范围内的小数位数统计功能。其中设置了上限值(如这里设定了最多不超过3000次),以防某些情况下可能出现周期性的无尽重复现象而导致死循环发生。 另外需要注意的是,在实际应用当中可能还会遇到其他特殊情况比如分母等于零等问题也需要提前做好异常处理工作以确保整个算法健壮性和可靠性。 #### 关键点解析 上述代码的关键在于利用取模操作 `%` 来获得每次相除后的余数值作为下一次新的分子参与新一轮计算直至达到终止条件即要么找到足够的有效小数位或者发现存在无法结束的情况才停止运行流程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值