【发布时间】:2013-05-01 03:04:12
【问题描述】:
我编写了一个程序,将数字分解为素数,然后将它们存储在一个向量中,最后询问是否通过将它们相乘来验证结果。
它是这样工作的:请求一个数字(代码中的num),然后将其除以 2 及以上。
如果它找到一个模数(当num mod divisor)为零的数字(代码中的divisor),则将该除数存储到一个向量中,并通过将num 除以@ 987654326@ 并将其存储到temp 中,并将除数重置为 1(while 循环中的最后一条语句将其递增为 2。如果找不到这样的数字,divisor 将增加直到大于或等于到num。这个过程一直持续到divisor大于num。
代码如下:
#include <iostream>
#include <vector>
using namespace std;
int main() {
//num=the number of interest
//divisor=the number dividing the number of interest each time
unsigned long divisor=2, num, temp ; //num=13699293826d
char c;
vector<unsigned long> divisors;
cout<<"Enter a number: "<<endl;
cin>>num;
//temp stores the number that is reduced each time
temp=num;
while(divisor<=num)
{
if(temp%divisor==0)
{
temp=temp/divisor;
divisors.push_back(divisor);
cout<<"one "<<divisor<<endl;
cout<<"the number of interest is now"<<temp<<endl;
divisor=1;
}
if(divisor==temp&&temp!=1)
{
cout<<"two " << divisor<<endl;
divisors.push_back(divisor);
}
divisor++;
}
if(divisors[0]==num)
{
cout<<"The number: "<<num<<" is prime. ";
}
else
{
cout<<"Its proper divisors are: ";
for(unsigned int count=0; count<divisors.size(); count++ )
{
cout<<divisors[count]<<"\t";
}
}
cout<<"Print out the multiplication? Press 'Y' or 'N'."<<endl;
cin>>c;
if(c=='Y'||c=='y')
{
for(unsigned int count=0; count<divisors.size(); count++)
{
temp*=divisors[count];
cout<<temp<<"\t";
}
}
return 0;
}
我已经打印了一些调试cout 语句。
我遇到的问题是:当数量足够大时,调试 声明“感兴趣的数量是现在”,后面有数字 1。 然后,程序崩溃了。
代码有什么问题?
谢谢。
是的,我在 64 位上运行它。
示例程序输出:
Enter a number:
13699293826
one 3
the number of interest is now: 1431655765
one 5
the number of interest is now: 286331153
one 17
the number of interest is now: 16843009
one 257
the number of interest is now: 65537
one 65537
the number of interest is now: 1
然后程序崩溃了。
我还注意到 3 的第一个“素因数”不正确,因为 13699293826 除以 3 是 4562761275.333333333333333.....
编辑#2--------------------------------------------------------
temp 65537, divisor 62287
..............omitted output
temp 65537, divisor 65530
temp 65537, divisor 65531
temp 65537, divisor 65532
temp 65537, divisor 65533
temp 65537, divisor 65534
temp 65537, divisor 65535
temp 65537, divisor 65536
temp 65537, divisor 65537
one 65537
the number of interest is now: 1
Its proper divisors are: 3 5 17 257 65537 Print out the multiplication? Press 'Y' or 'N'.
然后程序停止响应,按“y”回车也不行。
另外,相乘的数字也不正确;结果是 4294967295 ......在谷歌搜索后,它说它是“使用 32 位(二进制数字)可以获得的最高数字”。但是在我的电脑上,它说操作系统是 64 位的。
【问题讨论】:
-
您使用的是 64 位平台吗?
-
为什么不在
if(temp%divisor==0)语句块的顶部添加一个cout << "temp " << temp << ", divisor " << divisor << '\n';...然后您可以看到正在划分的数字以及temp结果是否有意义。最好编辑您的问题以包含导致崩溃的输出。您还可以在交互式调试器中观察执行情况,查看变量是否包含您期望的值,以及究竟是哪一行崩溃。 -
在 SO 上询问有关错误的问题时,您应该始终包含完整的错误消息。
-
在整个程序的任何地方都使用
unsigned long long。unsigned long仍然是 32 位。你的长号码被截断,变成了1431655765 * 3 = 4294967295 = 2^32 - 1。它就在您的输出中。它的因式分解确实是3,5,17,257,65537。
标签: c++ math prime-factoring