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

Is there a better way for me to go about this?

Thanks.

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

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
44
45
46
47
48
49
50
51
52
53
  // EulerProblemTHREE.cpp : Defines the entry point for the console application.
//

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

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<divisor; i++)
	{
		if (divisor % i == 0)
		{
			return false;
		}
	return true;
	}
}

void findDivisors()
{
	int ii;
// The section that I am unsure about is in the line below. You can see one of the ways I have attempted to solve the problem.
	for (ii=2; ii<= (sqrt((double)number)); ii++)
	{
		long long number;
		if (number % ii == 0)
		{
			primaryDivisors[countOfArray] = ii;
			countOfArray++;
			cout << "\t" << primaryDivisors[countOfArray-1];
			primaryDivisors[countOfArray] = number/ii;
			countOfArray++;
		}
	}
}

int main()
{
	findDivisors();
	cout << primaryDivisors[2];
	cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
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

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

1
2
3
4
5
6
7
8
9
10
11
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<int>(ceil(sqrt(static_cast<double>(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.