Rohan Bojja
Rohan Bojja

Reputation: 675

Calculating the number of perfect squares, perfect cubes,etc in a given range?

I know that we can use the formula math.floor(b**(1.0/i))-math.ceil(a**(1.0/i))+1 to calculate the number of squares in a given range, Does it hold when I want to find the number of perfect cubes,etc?

UPDATE: For all the people facing this issues, floor and ceil functions do not work well after square root, cube root, etc.

Upvotes: 1

Views: 546

Answers (1)

MBo
MBo

Reputation: 80267

Float numbers calculations are not exact.

64**1/3 could have value like ~3.99999975, so floor gives 3. Or 4.000000016, so ceil gives 5 (I did not check real value). You must take numerical errors into account.

For this task you can calculate root (using ** or Math.Pow), and check the difference with floor-ed and ceil-ed values. If difference is very small, check whether this root is exact one - in integers using multiplication.

Upvotes: 1

Related Questions