繁体   English   中英

C中阶乘的素数分解

[英]prime factorization of factorial in C

我正在尝试编写一个程序,它将以以下形式打印给定数字的阶乘: 10!=2^8 * 3^4 * 5^2 * 7 为了使其快速,假设给定数字是 10,我们事先有素数。 我不想先计算阶乘。 因为如果给定的数字更大,它最终会超出 int 类型的范围。 所以我遵循的算法是:首先计算二的幂。 一到十之间有五个数字,二分为五。 这些数字分别为 2*1、2*2、...、2*5。 此外,二也将集合 {1,2,3,4,5} 中的两个数相除。 这些数字是 2*1 和 2*2。 继续这种模式,二分为一和二之间的一个数。 那么a=5+2+1=8。

现在看看找到三的力量。 有从一到十的三个数字,三分为三,然后是一到三之间的一个数字,三分为一。 因此b=3+1=4。 以类似的方式 c=2。 那么集合 R={8,4,2,1}。 最后的答案是:

10!=2^8*3^4*5^2*7

所以我写的是:

#include <stdio.h>
main()
 {
     int i, n, count;
     int ara[]={2, 3, 5, 7};
     for(i=0; i<4; i++)
     {
         count=0;
         for(n=10; n>0; n--)
         {
            while(n%ara[i]==0)
            {
                count++;
                n=n/ara[i];
            }
         }
         printf("(%d^%d)" , ara[i], count);
     }
     return 0;
   }

输出为 (2^3) (3^2) (5^1) (7^1)。 我不明白我的代码有什么问题。 任何人都可以帮助我吗?

更简单的方法:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    const int n = 10;
    const int primes[] = {2,3,5,7};
    for(int i = 0; i < 4; i++){
        int cur = primes[i];
        int total = 0;
        while(cur <= n){
            total += (n/cur);
            cur = cur*primes[i];
        }
        printf("(%d^%d)\n", primes[i], total);
    }
    return 0;
}

当您的代码可被某个素数整除时,您的代码会除以 n,从而进行 n 次跳跃。

例如,当 n = 10 且 i = 0 时,您进入 while 循环,n 可被 2 整除 (arr[0]),导致 n = 5。因此您跳过了 n = [9..5)

你应该做的是你应该在划分时使用 temp ,如下所示:

#include <stdio.h>
main()
 {
 int i, n, count;
 int ara[]={2, 3, 5, 7};
 for(i=0; i<4; i++)
 {
     count=0;
     for(n=10; n>0; n--)
     {
        int temp = n;
        while(temp%ara[i]==0)
        {
            count++;
            temp=temp/ara[i];
        }
     }
     printf("(%d^%d)" , ara[i], count);
 }
 return 0;

}

用于查找无 pl 的阶乘。 试试这个代码:

#include <stdio.h>

int main()
{
  int c, n, fact = 1;

  printf("Enter a number to calculate it's factorial\n");
  scanf("%d", &n);

  for (c = 1; c <= n; c++)
    fact = fact * c;

  printf("Factorial of %d = %d\n", n, fact);

  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM