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.
// EulerProblemTHREE.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "math.h"
#include <iostream>
int countOfArray = 0;
usingnamespace std;
longlong number = 600851475143;
int primenumbers[300];
int primaryDivisors[15] = {0};
bool isPrime(longlong divisor)
{
int i;
for (i=2; i<divisor; i++)
{
if (divisor % i == 0)
{
returnfalse;
}
returntrue;
}
}
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++)
{
longlong 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;
}
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
inlineint 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
returnstatic_cast<int>(ceil(sqrt(static_cast<double>(m))));
}
// etc
for (int ii=2, mm=approx_sqrt(number); ii<=mm; ++ii) // pre-inc is better!
{