Skip to content

Commit

Permalink
Merge e12f8ea into 314b93e
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 4, 2019
2 parents 314b93e + e12f8ea commit fa9a444
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,4 +375,5 @@ problems from
* [Day 377](https://github.com/vaskoz/dailycodingproblem-go/issues/760)
* [Day 378](https://github.com/vaskoz/dailycodingproblem-go/issues/762)
* [Day 379](https://github.com/vaskoz/dailycodingproblem-go/issues/764)
* [Day 380](https://github.com/vaskoz/dailycodingproblem-go/issues/766)

43 changes: 43 additions & 0 deletions day380/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package day380

// DivisionBrute returns the quotient and remainder of division
// without using the division operator using brute-force.
func DivisionBrute(dividend, divisor int) (int, int) {
if divisor == 0 {
panic("divide by zero")
}

var dividendNeg, divisorNeg bool

if dividend < 0 {
dividendNeg = true
dividend = -dividend
}

if divisor < 0 {
divisorNeg = true
divisor = -divisor
}

var quotient int

for dividend >= 0 {
dividend -= divisor
quotient++
}

remainder := dividend + divisor
quotient--

if dividendNeg {
quotient = -quotient
remainder = -remainder
}

if divisorNeg {
quotient = -quotient
remainder = -remainder
}

return quotient, remainder
}
44 changes: 44 additions & 0 deletions day380/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package day380

import "testing"

// nolint
var testcases = []struct {
dividend, divisor int
quotient, remainder int
}{
{10, 3, 3, 1},
{9, 3, 3, 0},
{-9, 3, -3, 0},
{9, -3, -3, 0},
{-9, -3, 3, 0},
}

func TestDivisionBrute(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if q, r := DivisionBrute(tc.dividend, tc.divisor); q != tc.quotient || r != tc.remainder {
t.Errorf("Expected (%v,%v), got (%v,%v)", tc.quotient, tc.remainder, q, r)
}
}
}

func TestDivisionBruteDivideByZero(t *testing.T) {
t.Parallel()

defer func() {
if err := recover(); err == nil {
t.Errorf("expected a panic when divisor is zero")
}
}()
DivisionBrute(1, 0)
}

func BenchmarkDivisionBrute(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
DivisionBrute(tc.dividend, tc.divisor)
}
}
}

0 comments on commit fa9a444

Please sign in to comment.