Fixed Issue #5 - Factorial loop can be start from 2
This commit is contained in:
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
@rem
|
git @rem
|
||||||
@rem Copyright 2015 the original author or authors.
|
@rem Copyright 2015 the original author or authors.
|
||||||
@rem
|
@rem
|
||||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
|||||||
@@ -14,8 +14,12 @@ class Factorial {
|
|||||||
* @return returns the factorial of a number by an iterative method
|
* @return returns the factorial of a number by an iterative method
|
||||||
*/
|
*/
|
||||||
fun compute(number: Int) : Int {
|
fun compute(number: Int) : Int {
|
||||||
|
if (number <= 1) {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
var result = 1
|
var result = 1
|
||||||
for (i in 1..number) {
|
for (i in 2..number) {
|
||||||
result *= i
|
result *= i
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
@@ -25,6 +29,7 @@ class Factorial {
|
|||||||
* worst time: O(n)
|
* worst time: O(n)
|
||||||
* amount of memory: O(n) - stack for recursion
|
* amount of memory: O(n) - stack for recursion
|
||||||
*
|
*
|
||||||
|
* @return returns factorial recursively
|
||||||
*/
|
*/
|
||||||
fun computeRecursive(number: Int) : Int {
|
fun computeRecursive(number: Int) : Int {
|
||||||
return if (number <= 1) {
|
return if (number <= 1) {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ internal class FactorialTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_iterative() {
|
fun test_iterative() {
|
||||||
|
assertEquals(1, factorial.compute(0))
|
||||||
|
assertEquals(1, factorial.compute(1))
|
||||||
assertEquals(6, factorial.compute(3))
|
assertEquals(6, factorial.compute(3))
|
||||||
assertEquals(120, factorial.compute(5))
|
assertEquals(120, factorial.compute(5))
|
||||||
assertEquals(720, factorial.compute(6))
|
assertEquals(720, factorial.compute(6))
|
||||||
@@ -16,6 +18,8 @@ internal class FactorialTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun test_recursive() {
|
fun test_recursive() {
|
||||||
|
assertEquals(1, factorial.compute(0))
|
||||||
|
assertEquals(1, factorial.compute(1))
|
||||||
assertEquals(6, factorial.computeRecursive(3))
|
assertEquals(6, factorial.computeRecursive(3))
|
||||||
assertEquals(120, factorial.computeRecursive(5))
|
assertEquals(120, factorial.computeRecursive(5))
|
||||||
assertEquals(720, factorial.computeRecursive(6))
|
assertEquals(720, factorial.computeRecursive(6))
|
||||||
|
|||||||
Reference in New Issue
Block a user