Skip to content

Commit d17a097

Browse files
author
Dmitry
committed
Fixed Issue DmitryTsyvtsyn#5 - Factorial loop can be start from 2
1 parent 5ce2539 commit d17a097

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

gradlew.bat

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
@rem
1+
git @rem
22
@rem Copyright 2015 the original author or authors.
33
@rem
44
@rem Licensed under the Apache License, Version 2.0 (the "License");

src/main/kotlin/other/Factorial.kt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,12 @@ class Factorial {
1414
* @return returns the factorial of a number by an iterative method
1515
*/
1616
fun compute(number: Int) : Int {
17+
if (number <= 1) {
18+
return 1
19+
}
20+
1721
var result = 1
18-
for (i in 1..number) {
22+
for (i in 2..number) {
1923
result *= i
2024
}
2125
return result
@@ -25,6 +29,7 @@ class Factorial {
2529
* worst time: O(n)
2630
* amount of memory: O(n) - stack for recursion
2731
*
32+
* @return returns factorial recursively
2833
*/
2934
fun computeRecursive(number: Int) : Int {
3035
return if (number <= 1) {

src/test/kotlin/other/FactorialTest.kt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,17 @@ internal class FactorialTest {
99

1010
@Test
1111
fun test_iterative() {
12+
assertEquals(1, factorial.compute(0))
13+
assertEquals(1, factorial.compute(1))
1214
assertEquals(6, factorial.compute(3))
1315
assertEquals(120, factorial.compute(5))
1416
assertEquals(720, factorial.compute(6))
1517
}
1618

1719
@Test
1820
fun test_recursive() {
21+
assertEquals(1, factorial.compute(0))
22+
assertEquals(1, factorial.compute(1))
1923
assertEquals(6, factorial.computeRecursive(3))
2024
assertEquals(120, factorial.computeRecursive(5))
2125
assertEquals(720, factorial.computeRecursive(6))

0 commit comments

Comments
 (0)