【发布时间】:2020-03-21 13:29:30
【问题描述】:
首先,我要澄清一下,我是编程新手,最近开始接触 c++。我的数学课本里有一个与勒让德公式有关的问题,我想制作一个与之相关的程序。它从用户 n 中获取一个数字,并找到 n 的最大幂除以 n!
它对于很多数字都运行良好,但对于其他一些数字来说却是混乱的,而且它是完全随机的。这是代码中的一个sn-p。
#include <iostream>
#include <math.h>
using namespace std;
int prime(int);
int calc(int, int);
int main()
{
int n;
int hpf=2;
cout<<"This program finds highest power x that divides x!"<<endl;
cout << "Enter number : " << endl;
cin>>n;
for(int i=2; i<=n; i++)
{
bool p=prime(i);
if(p==true && n%i==0)
hpf=i;
}
cout<<"The highest prime factor of the number is : "<<hpf<<endl;
int p=calc(hpf, n);
cout<<"The highest power of "<<n<<" that divides "<<n<<"!"<<" is : "<<p;
return 0;
}
calc(int f, int n)
{
int c=0 , d=1, power=1, i=0;
while(i>=0)
{
int x= pow(f,power+i);
if(i>0 && n%x==0)
d++;
if(x<=n)
{
c+=n/x;
i++;
}
else
break;
}
return c/d;
}
prime(int n)
{
bool isPrime = true;
for(int i = 2; i <= n/2; i++)
{
if (n%i == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
我将 n 的最高质因数和数字 n 本身传递给 int calc(int, int)。
现在问题来了:
当我输入 n=9 时,我得到
Enter number :
9
The highest prime factor of the number is : 3
The highest power of 9 that divides 9! is : 2
另一方面,如果我输入 25,我得到
Enter number :
25
The highest prime factor of the number is : 5
The highest power of 25 that divides 25! is : 6
这显然是错误的,最高的应该是3。
它也可以准确地处理更大的数字,但不是全部。
PS:我使用代码块。
【问题讨论】:
-
您可能想检查
int在您的平台上可以容纳的最大数字是多少,看看是否是 25!适合int。我的猜测是你运气不好。 numeric_limits/max -
25!也不适合 64 位变量。
-
另外请记住,
pow是一个双精度浮点函数,因此可能不完全准确(并且不能准确表示大的 64 位整数)。 -
是的,可能。或者至少,如果可以的话,Minimal, Reproducible Example。
-
至于奇普斯特的评论:最大因子不会大于
n / 2,但你只需要检查i*i <= n的数字,因为如果n可以被i整除表示i*j == n。现在i将小于sqrt(n)并且j将大于除非n是正方形并且i == j。但请注意:sqrt()也是一个浮点函数,可能与pow有类似的问题...