How to get n power ( square of a number or cube etc.) of a number in flutter?
You are looking for this: https://api.dartlang.org/stable/2.5.0/dart-math/pow.html so:
pow(X,N)
If you want to implement it, you can have a look at here: https://coflutter.com/challenges/dart-how-to-implement-exponential-function-power/ This boils down to this loop:
int power(int x, int n) {
int retval = 1;
for (int i = 0; i < n; i++) {
retval *= x;
}
return retval;
}
This only works well for integer n-s.
For all of these examples with pow
you need the following import:
import 'dart:math';
8²
final answer = pow(8, 2); // 64
Notes:
If you are only squaring, then it's probably easier to do this:
final answer = 8 * 8;
answer
is inferred to be of typenum
, which could be anint
ordouble
at runtime. In this case the runtime type isint
, but in the following two examples it isdouble
.
Fourth root of 256
final answer = pow(256, 1/4); // 4.0
0.2^(-3)
final answer = pow(0.2, -3); // 124.99999999999999
That's basically the same as five cubed.