I’m stuck on this question from a mock exam paper. I need to multiply a ‘from’ number to a ‘n’ number. In other words: from*(from+1)(from+2)…*n.
I need to solve this problem by using a while loop. I have done this so far and not sure what to do.
class Fact {
private int factPartND(final int from, final int n) {
int c = 1;
int z = from;
int y = n;
int num = 0;
while (y >= z) {
num += from * (from + c);// need to stop multiplying from for each
// iteration?
c++;
y--;
}
return num;
}
public static void main(String[] args) {
Fact f = new Fact();
int test = f.factPartND(5, 11);
System.out.println(test);
}
}
Your computation is:
Think of each factor as one iteration of your loop.
So your second iteration should be multiplying your accumulated value by
(from + 1), later another iteration by(from + i), wherefrom < i < n, and so on until you multiply your accumulated value by(from + n).Your code is very close – you have
(from + c)in every iteration, but your arithmetic is wrong.And as has been mentioned, it’s a bit confusing to use
candyto keep track of your loop, when it’s sufficient to just testc.