gpt4 book ai didi

c++ - 使用筛法进行素因数分解

转载 作者:行者123 更新时间:2023-11-30 20:57:00 25 4
gpt4 key购买 nike

我的代码有什么问题吗?
我试图找到素因数,但在获取输入后它崩溃了,它不起作用。

我现在应该做什么?我在生成素数后使用单独的方法生成素数,我只是在 main 中调用素数函数。

#include<iostream>
#include<cstdio>
#include<math.h>
#define SIZE 1000000
using namespace std;
long p[SIZE],input;
long List[SIZE]; // saves the List
long listSize; // saves the size of List

void prime(void)
{
long i,j;
p[0]=1;
p[1]=1;
for(i=2;i<=sqrt(SIZE);i++) // prime generate part
if(p[i]==0)
for(j=2;j*i<=SIZE;j++)
p[i*j]=1;
}

void primeFactorize( long n )
{
listSize = 0; // Initially the List is empty, we denote that size = 0
long sqrtN = long( sqrt(n) ); // find the sqrt of the number
for( long i = 0; p[i] <= sqrtN; i++ ) { // we check up to the sqrt
if( n % p[i] == 0 ) { // n is multiple of prime[i]
// So, we continue dividing n by prime[i] as long as possible
while( n % p[i] == 0 ) {
n /= p[i]; // we have divided n by prime[i]
List[listSize] = p[i]; // added the ith prime in the list
listSize++; // added a prime, so, size should be increased
}
// we can add some optimization by updating sqrtN here, since n
// is decreased. think why it's important and how it can be added
}
}
if( n > 1 )
{
// n is greater than 1, so we are sure that this n is a prime
List[listSize] = n; // added n (the prime) in the list
listSize++; // increased the size of the list
}
}
int main()
{
prime();
while(scanf_s("%ld",&input),input)
{
if(input==1)
printf("1 = 1\n");
else if(input==-1)
printf("-1 = -1 x 1\n");
else
{
primeFactorize( input );

}
for( long i = 0; i < listSize; i++ ) // traverse the List array
printf("%d ", List[i]);

}
return 0;
}

最佳答案

void prime(void){
long i,j;
p[0]=1;
p[1]=1;
for(i=2;i<=(long)sqrt((double)SIZE);i++)
if(p[i]==0)
for(j=2;j*i<SIZE;j++)//<=SIZE ---> <SIZE
p[i*j]=1;
}

void primeFactorize( long n ){
listSize = 0;
long sqrtN = (long)sqrt((double)n);//
for( long i = 2; i <= sqrtN; i++ ) { //i = 0 ---> i = 2 and p[i] ---> i (Same below)
while( n % i == 0 ) {//possible [if statement] is omitted
n /= i;//!
List[listSize] = i;//!
listSize++;
}
}
if( n > 1 )
{
List[listSize] = n;
listSize++;
}
}

关于c++ - 使用筛法进行素因数分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17006745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com