Alternate solution using sieve approach and buffered output