Stack overflow (parameters: 0x00000001, 0x00442FF8)

3

Algorithm checks if both variables "a" and "x" are prime numbers.If yes, it simply announce that these are prime.Need 50 of them, when it comes to 6th position program shows an error:

Exception thrown at 0x00D02509 in ConsoleApplication3.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x002D2F5C). Unhandled exception at 0x00D02509 in ConsoleApplication3.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x002D2F5C).

#include "stdafx.h"
#include <iostream>

using namespace std;


int CheckIfPrime(long int n)
{
    if (n<2) return 0;
    for (int i = 2; i*i <= n; i++)
        if (n%i == 0) return 0;
    return 1;
}

int pow(int ap, int nt)
{
    if (nt == 0)
        return 1;
    else
        return ap *= pow(ap, --nt);
}

void CountA(int *aValue, int x)
{
    *aValue = (pow(2, x) - 1);
}

int main()
{
    int x = 1;
    int a = 0;
    int *aPointer = &a;
    for (int i = 0; i <= 50;)
    {
        x++;
        if (CheckIfPrime(x))
        {
            CountA(aPointer, x);
            if (CheckIfPrime(a))
            {
                cout << i << ". X = " << x << " a = " << a  << " are prime " << endl;
                    i++;
            }
        }
        else
        {
            cout << "";
        }
    }
    getchar();
    return 0;
}
c++
asked on Stack Overflow Dec 10, 2015 by Johny Lavers • edited Mar 30, 2019 by StaceyGirl

2 Answers

1

You have stack overflow in function:

int pow(int ap, int nt)
{
  if (nt == 0)
    return 1;
  else
    return ap *= pow(ap, --nt);
}

for very large nt it will enter too deeply in recursion causing SO

answered on Stack Overflow Dec 10, 2015 by marcinj
0

You are trying to compute exact integer 2 to the power x for some rather large values of x. No ordinary data type can hold that value. But if you had some data type holding that value, then testing whether the result minus one is prime by that simplistic method would take more time than the life of the universe.

You are attacking a very hard and very well studied problem, and using nothing but naive ignorance as a tool.

https://primes.utm.edu/mersenne/

answered on Stack Overflow Dec 10, 2015 by JSF

User contributions licensed under CC BY-SA 3.0