Reputation: 1031
I have two values one for base that is X and one for power N, how can a get X to the power of N ans.
any code will be appreciated.
Upvotes: 18
Views: 28329
Reputation: 6958
Just as a reminder, when you are interested in the powers of two, you don't need the math
library, and you can use bit manipulation and left shift:
1 << 0 // 1
1 << 1 // 2
1 << 2 // 4
// ...
1 << 5 // 32
// ...
1 << 10 // 1024
Upvotes: 3
Reputation: 1
void main()
{
int m, n;
print("Enter 2 numbers: ");
m = int.parse(stdin.readLineSync()!);
n = int.parse(stdin.readLineSync()!);
int power = 1;
for (int i = 1; i <= n; i++) {
power = power * m;
}
print(power);
}
Upvotes: 0
Reputation: 512346
For all of these examples with pow
you need the following import:
import 'dart:math';
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 type num
, which could be an int
or double
at runtime. In this case the runtime type is int
, but in the following two examples it is double
.
final answer = pow(256, 1/4); // 4.0
final answer = pow(0.2, -3); // 124.99999999999999
That's basically the same as five cubed.
Upvotes: 18
Reputation: 1031
btw Its working fine for double also
double power() {
double x= double.parse(t1.text);
int y= int.parse(t2.text);
double power = 1;
for (double i = 0; i < y; i++) {
power *= x;
} ;
return power;
}
Upvotes: 0
Reputation: 1092
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.
Upvotes: 20