Friday, 6 September 2013

Sum of Powers of two Integers using only For-Loops

Sum of Powers of two Integers using only For-Loops

The question here would be to get the sum of powers (m^0 + m^1 + m^2 +
m^3.... + m^n) using only FOR loops. Meaning, not using any other loops as
well as Math.pow();
Is it even possible? So far, I am only able to work around getting m^n,
but not the rest.
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
int total = 1;
System.out.print("Enter value of m: ");
int m = scn.nextInt();
System.out.print("Enter value of n: ");
int n = scn.nextInt();
for (int i = 1; i <= n; i++){
total * m;
}
System.out.print(total);
}
Let's say m =8; and n = 4;
i gives me '1,2,3,4' which is what I need, but I am unable to power m ^ i.
Would be nice if someone could guide me into how it could be done, can't
seem to progress onwards as I have limited knowledge in Java.
Thanks in advance!

No comments:

Post a Comment