Prime with arrays please help!

Hello I,ve written this program that can calculate any Mersenne number.
The problem is that when I run it and tell it to calculate M6972593 it takes way too long (about five days!) what can I do to improve the speed of this program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <fstream>
// Mersene Prime Calculator
using namespace std;
 
int main ()
{
	ofstream file;
    file.open("Prime.txt");
	int i,counter,power,length;
	cout<<"Enter power of 2"<<endl;
	cin>>power;
	length=ceil(floor(power*log10(2)+1)/18);
	cout<<length;
	long long int *array = new long long int[length];
	for(i=0;i<length;i++)
	{
		array[i]=0;
	}
	array[length-1]++;
	for(counter=0;counter<power;counter++)
	{
		for(i=0;i<length;i++)
		{
			array[i]*=2;
		}
		for(i=length-1;i>0;i--)
		{
			if(array[i]>=pow(10,18))
			{array[i-1]=array[i-1]+(floor (array[i]/pow(10,18)));array[i]=array[i]-((floor (array[i]/pow(10,18)))*pow(10,18));}	
		}
	}
	for(i=0;i<length-1;i++)
	{
		file<<array[i];
	}
	file<<--array[length-1]<<endl;
	file.close();
	delete[] array;
	return 0;
}
Last edited on
The first thing I notice is that you call pow(10,18) over and over again.
Every time you call the std::pow() function, time is wasted recalculating 10 to the power of 18.

So why not just store the result into a constant, then use the constant instead of the function call:

const double ten_pow = pow(10, 18);

Also be sure to turn on Optimizations in your compiler settings.
If using GCC, compile with the -O3 flag.
If using Visual Studio, compile in Release mode.

Unfortunately I can't help you more, because I don't know how to improve the algorithm itself.
Or as an alternative to
 
const double ten_pow = pow(10, 18);
maybe
 
const double ten_pow = 1e18;
Topic archived. No new replies allowed.