PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

[FIXED] How to evaluate if a number is cube

 August 09, 2022     c#, decimal, double, integer, math     No comments   

Issue

I'm trying to calculate the cube root of a number to check if it's a perfect cube. Unfortunately the .NET Framework has no built-in function for that. So in order to calculate the cube root of a number I have to use the Math.Pow function:

double cubeRoot = Math.Pow(125, (double)1 / 3);

When I try to evaluate if the cube root is an integer it outputs false, yet 125 is a perfect cube:

Console.WriteLine(cubeRoot % 1 == 0);

How can I overcome this issue?


Solution

You need to round and check if the cube of the cube root is equal to the original value

double input = 125;
double cubeRoot = Math.Pow(input, 1.0/3.0);
double c = Math.Round(cubeRoot);
Console.WriteLine(c*c*c == input);

Note that Math.Pow(input, 1.0/3.0) is not the most accurate way to calculate cube root because 1.0/3.0 is not exactly representable in binary (and decimal). But since we're rounding the result to int anyway, the output will not be affected

.NET Core 2.1 added Math.Cbrt(double) which can be used to get a correct result in double precision, though I'm not sure if it's faster than the Math.Pow() solution or not



Answered By - phuclv
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing