From 5f65b35b9c9d8ce8dca67ada76171c8bd1cc204e Mon Sep 17 00:00:00 2001 From: filifa Date: Wed, 1 Oct 2025 23:27:32 -0400 Subject: [PATCH] buffer channel --- cmd/totient.go | 2 +- internal/lib/totient.go | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/cmd/totient.go b/cmd/totient.go index 74375db..f1d9afd 100644 --- a/cmd/totient.go +++ b/cmd/totient.go @@ -31,7 +31,7 @@ func totient(cmd *cobra.Command, args []string) { bufStdout := bufio.NewWriter(os.Stdout) defer bufStdout.Flush() - for v := range lib.TotientSieve(totientN) { + for v := range lib.TotientSieve(totientN, 1000) { if v == 0 { continue } diff --git a/internal/lib/totient.go b/internal/lib/totient.go index 85629da..7fbb0ee 100644 --- a/internal/lib/totient.go +++ b/internal/lib/totient.go @@ -17,9 +17,9 @@ along with this program. If not, see . package lib /* -TotientSieve computes totient(k) for k=1 to n, where totient is Euler's totient function. +TotientSieve computes totient(k) for k=1 to n, where totient is Euler's totient function. buflen sets the buffer length of the returned channel. Larger buffer lengths can result in better performance at the cost of higher memory usage. */ -func TotientSieve(n uint) chan uint { +func TotientSieve(n uint, buflen uint) chan uint { totients := make([]uint, n) totients[0] = 0 totients[1] = 1 @@ -27,20 +27,19 @@ func TotientSieve(n uint) chan uint { totients[i] = i - 1 } - ch := make(chan uint) + ch := make(chan uint, buflen) go func() { + defer close(ch) for i := uint(0); i < n; i++ { ch <- totients[i] if i == 0 || i == 1 || totients[i] != i-1 { continue } - for j := uint(2 * i); j < n; j += i { + for j := 2 * i; j < n; j += i { totients[j] -= totients[j] / i } } - - close(ch) }() return ch