Static casting to <int> in a for loop?

Dec 14, 2010 at 11:48pm
I'm doing a sieve of eratosthenes problem and I'd like to loop to sqrt(number). Is it possible to do this in the loop with the sqrt() function provided by math.h? I'd ideally like to be able to not have to make another variable in my function and instead just do it in the loop like this:

for (__int64 x=0; x<sqrt(num)); x++)

The problem is that x is an integer (doesn't matter if it's 32 bit) and sqrt returns a double. Do I need to cast it to something different? Hints appreciated.
Last edited on Dec 14, 2010 at 11:49pm
Dec 14, 2010 at 11:54pm
Hate replying to myself, but to give you an idea, this is what I'd have to do otherwsie:

1
2
3
4
5
6
7
8
int stopper = static_cast<int>(sqrt(static_cast<double>(Tn)));
	for (__int64 x=0; x<stopper; x++)
	{
		if (Tn%myvector.at(x) ==0)
		{
			cout<<myvector.at(x)<<" ";
		}
	}
Last edited on Dec 14, 2010 at 11:55pm
Dec 14, 2010 at 11:58pm
Do it the way in your most recent post.

You don't want to call sqrt() directly in your for loop because then the sqrt can be calculated every single time the loop iterates (which is wasteful). It's better to calculate the sqrt ahead of time and stuff it in a var, then use the var in the loop.
Dec 15, 2010 at 2:21am
Ah, that makes sense! Thanks. I figured there may have been a better way to do it.
Topic archived. No new replies allowed.