0

I have written the phi function in C++, but my program crashes if I declare the array phi with 1.000.000 elements. It does not give me any errors and works fine if I reduce it to 99.999 elements. Can someone suggest me any optimization to the code? It is all school-related.

    #include <iostream>
using namespace std;
int main()
{
    int M;
    cin >> M;
    int phi[1000000];
    for (int i = 1; i <= M; ++i)
        phi[i] = i-1;
    for (int i = 2; i <= M; ++i)
        for (int j = 2*i; j <= M; j += i)
            phi[j] -= phi[i];
    cout << phi[M];
}
Söraka
  • 53
  • 1
  • 5
  • Well, consider the array to be of size 10, then you can access index 0 to 9 I.e. `phi[0] to phi[9]` . Here your for loop is running from 1 to 10 I.e. `M` , and 10 is not accessible , so it crashes. Either make M from 0 to 9, or declare phi to be of size 11. – algrebe Oct 30 '16 at 17:11
  • Your are trying to allocate 4 gigs of memory on the stack. And you do not have enough space on it. Allocate your `phi` in heap using `new` operator. – Dmitry Katkevich Oct 30 '16 at 17:13
  • Actually, Dmitry Katmevich, its only 4megs, but thats around the size of default stack size. – UldisK Oct 30 '16 at 17:57

0 Answers0