You are using a version without Ads of this website. Please, consider donating:

### Square root of an integer variable

Hi there;
While I was attempting Project Euler Problem Number three, I encountered a problem.

I have an int value, and I want to try and square root this, however I am unsure how I can go about converting it into a double/float variable type in order to achieve this using the sqrt function in math.h

Thanks.

Note: This code isn't finished, there are still other functions I need to add in in order to complete the task.

 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 // EulerProblemTHREE.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "math.h" #include int countOfArray = 0; using namespace std; long long number = 600851475143; int primenumbers[300]; int primaryDivisors[15] = {0}; bool isPrime(long long divisor) { int i; for (i=2; i
Last edited on
 I am unsure how I can go about converting it into a double/float variable type
The conversion is done automatically as always from smaller to bigger type.

Better calculate the sqrt() once before the loop (saves time)

the return on line 23 ends the loop. I guess you want to move that line below the loop
Or you could use this form

 12 for (int ii=2, mm=(int)sqrt((double)number); ii<= mm; ii++) {

as neither ii nor mm are needed outside of the scope of the for-loop.

Even better, write a little helper function to tidy things up (hide the casting.)

 1234567891011 inline int approx_sqrt(int m) { // now using modern C++ casts and ceil, to make sure the // returned value is always the integer just above the square root return static_cast(ceil(sqrt(static_cast(m)))); } // etc for (int ii=2, mm=approx_sqrt(number); ii<=mm; ++ii) // pre-inc is better! {

Andy

ceil (from <cmath>)
http://www.cplusplus.com/reference/cmath/ceil/
Last edited on
Topic archived. No new replies allowed.