You're okay to independently and entirely re-implement an existing algorithm, and then copyright your code, as long as the algorithm isn't patented.
For example, the lzw compression algorithm used by gif was patented (the patent expired ~2004). And therefore, (a) you couldn't copyright an independently-written gif generator or viewer, and (b) you couldn't even write one without copyrighting it, and just give the code away.
And assuming no patent, then to be completely safe about copyright violation, you'd be best off reading a textbook discussion of the algorithm in a cleanroom-like fashion, e.g., https://en.wikipedia.org/wiki/Clean_room_design , rather than poring over already-copyrighted code for long hours.