-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #480 from vaskoz/day233
Day233
- Loading branch information
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package day233 | ||
|
||
import "errors" | ||
|
||
var errOverflow = errors.New("overflow occurred") | ||
|
||
// ErrOverflow represents an overflow error. | ||
func ErrOverflow() error { | ||
return errOverflow | ||
} | ||
|
||
// FastFibonnaci runs in O(N) time with O(1) space. | ||
// Returns an error if overflow occurs. | ||
func FastFibonnaci(n uint) (uint, error) { | ||
if n < 2 { | ||
return n, nil | ||
} | ||
first, second := uint(0), uint(1) | ||
var err error | ||
for i := uint(1); i < n; i++ { | ||
first, second = second, first+second | ||
if second < first { | ||
return 0, errOverflow | ||
} | ||
} | ||
return second, err | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package day233 | ||
|
||
import "testing" | ||
|
||
var testcases = []struct { | ||
n, fib uint | ||
err error | ||
}{ | ||
{0, 0, nil}, | ||
{1, 1, nil}, | ||
{2, 1, nil}, | ||
{12, 144, nil}, | ||
{28, 317811, nil}, | ||
{44, 701408733, nil}, | ||
{87, 679891637638612258, nil}, | ||
{100, 0, ErrOverflow()}, | ||
} | ||
|
||
func TestFastFibonnaci(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
if result, err := FastFibonnaci(tc.n); result != tc.fib || err != tc.err { | ||
t.Errorf("Given n=%d, expected (%d,%v), got (%d,%v)", tc.n, tc.fib, tc.err, result, err) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkFastFibonnaci(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
FastFibonnaci(tc.n) //nolint | ||
} | ||
} | ||
} |