-3

I am stuck on trying to get the sieve to work. When I debug it, it tells me that stuff like 9 and 15 still evaluate to true when they go through the sieve. What causes this? Also, am I using the vector properly to get the highest prime factor?

#include <iostream>
#include <vector>
#include <math.h>

int main()
{
    long long n = 13195;
        long long sqrtn = sqrt(n);

        bool* boolarray = new bool[n];

        for(long long i = 0; i<=boolarray[sqrtn]; i++) {
                boolarray[i] = true;
        }

        long long x = 0;

        for(long long i=2; i<=sqrtn; i++) {
                if(boolarray[i]) {
                        for(long long j=pow(i, 2)+x*i; j<=n; j=pow(i, 2)+(++x*i))

                                        boolarray[j] = false;
                }
        }

        std::vector<long> primefactors;

        for(long long i = 0; i<=sqrtn; i++)
        {
                if(boolarray[i] && n % boolarray[i] == 0)
                        primefactors.push_back(i);
        }

        int answer = primefactors.back();

        printf("Answer: %i\n", answer);

        _sleep(10000);

        delete[] boolarray;

    return 0;
}
4

1 回答 1

1

The following is wrong:

                    for(long long j=pow(i, 2)+x*i; j<=n; j=pow(i, 2)+(++x*i))

Both the initial value and the update expression for j are incorrect. I leave it as an exercise to figure out what exactly is wrong, and how to fix it.

于 2013-03-03T21:06:46.570 回答