Answer the question
In order to leave comments, you need to log in
How to reduce program execution time [C++]?
Hello. Help reduce the program running time by ~0.014 seconds.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n,S,c;
cin >> n;
for(long i=1; i<=n; i++)
{
c = pow(i,0.5);
if(i==1)
{S=4;}
else if(i==c*c+1||i==c*c+c+1)
{S+=3;}
else{S+=2;}
}
cout << S << "\n";
return 0;
}
Answer the question
In order to leave comments, you need to log in
First of all.
Instead
Second, cache the c*c expression. The multiplication operation is expensive.
Thirdly, your first if works only on the first iteration, start iterations from 2.
Fourthly, if possible, you should use OpenMP, and even better OpenCL
This is about programming techniques. But it seems to me that if you dig into the math,. then you can change the algorithm.
About how, after re-formatting the question, I saw the task itself. Then it is definitely worth starting the enumeration
from s*s, whereint s =sqrt(n);
you can try replacing if with something else. e.g. switch
Help reduce the program running time by ~0.014 seconds.
I would loop not over i to n, but through c until c*c < n. The code itself will be more complicated, but, firstly, the loop will be executed fewer times, and secondly, you will save the slow operation of raising to an arbitrary power.
Obviously, the longest operation is user input, so you need to type the number faster =)
Joking aside. First, make sure you are building the project with optimization enabled. For example, my old Core2Duo for n=999999 gives the answer in almost a second after I built your program with O2.
ps. To post code in a question, you do not need to insert it as an image - just wrap it in a code tag (look at the buttons available in the post editor).
.statiya h1 {}
.statiya p {}
...
.statiya {}
.statiya_title {}
.statiya_text {}
...
h1, p, img {
margin:5px 10px; padding:6px 5px 6px 65px; font-size:15px;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question