L
L
LanternOfDarkness2014-11-03 20:26:58
C++ / C#
LanternOfDarkness, 2014-11-03 20:26:58

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;
}

Condition: It is necessary to calculate the minimum number of square sides for a given number of squares n(1<=n<=10^9). In this case, only squares with a side of 1 are considered a square. It must be performed in less than 1 second.

Answer the question

In order to leave comments, you need to log in

8 answer(s)
D
DancingOnWater, 2014-11-04
@LanternOfDarkness

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);

D
Dmitry Skrylnikov, 2014-11-03
@worlxxaker

you can try replacing if with something else. e.g. switch

J
jcmvbkbc, 2014-11-03
@jcmvbkbc

Help reduce the program running time by ~0.014 seconds.

Run it with less n.
But seriously, start from the beginning - what did you want to calculate?

S
SHVV, 2014-11-03
@SHVV

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.

B
bogolt, 2014-11-04
@bogolt

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).

A
Andrey B., 2017-01-09
@Faraon83

.statiya h1 {}
.statiya p {}
...

Or what did I not understand?
So it's still possible
.statiya {}
.statiya_title {}
.statiya_text {}
...

Y
Yevgeniy Kisselyov, 2017-01-09
@ewgenio

h1, p, img {
margin:5px 10px; padding:6px 5px 6px 65px; font-size:15px;
}

S
Stanislav, 2017-01-09
@Faraon83

The tags didn't register. Here I repeat
div class="po-statiya"
My main text
is h2 heading 2 h2
p Some more text p
/div

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question