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