Equivalent product

De Software testing
Ir para: navegação, pesquisa

Consider the following versions of the Factorial program.

public class Factorial {
	public static long compute (int x)
		throws NegativeNumberException {
		if (x >= 0) {
			long r = 1;
			for (int k = 2 ; k <= x ; k++) {
				r *= k ;
			}
			return r ;
		} else {
			throw new NegativeNumberException() ;
		}
	}
}


public class Factorial {
	public static long compute (int x)
		throws NegativeNumberException {
		if (x >= 0) {
			long r = 1;
			for (int k = 1 ; k <= x ; k++) {
				r *= k ;
			}
			return r ;
		} else {
			throw new NegativeNumberException() ;
		}
	}
}

Observe that the only difference is the assignment in line 6 which initializes k with 1 instead of 2. Although the former version performs one additional step when calculating the factorial function, the resulting value is always the same, regardless of the value of x. Thus this version is equivalent to the previously mentioned correct version.