Fixed Issue #5 - Factorial loop can be start from 2

This commit is contained in:
Dmitry
2022-01-30 18:46:59 +07:00
parent 5ce2539162
commit d17a097cbc
3 changed files with 11 additions and 2 deletions

2
gradlew.bat vendored
View File

@ -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");

View File

@ -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) {

View File

@ -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))