Apparently I am attempting to access a memory adress that hasn't been allocated. Can someone please tell me where? (The program to prime factorize n given numbers)
#include <iostream>
using namespace std;
void sieve(int n){
int primes[n + 1];
for(int i = 2; i <= n; i++){
primes[i] = i;
}
for(int i = 2; i <= n; i++){
if(primes[i] == i){
for(int j = i*i; j <= n; j += i){
if(primes[j] == j){
primes[j] = i;
}
}
}
}
while(n != 1){
cout << primes[n] << " ";
n /= primes[n];
}
cout << endl;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie();
int n;
cin >> n;
for(int i = 0; i < n; i++){
int x;
cin >> x;
sieve(x);
}
}
This loop is very suspect:
while(n != 1){
cout << primes[n] << " ";
n /= primes[n];
}
How sure are you that n won't become 0? And you haven't initialized primes[0] to anything, so it could be any random value. At that point, n becomes who knows what, and you're off in la-la land.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.