Search code examples
javagreatest-common-divisor

Calculating Table of Common Factors in Java


I'm trying to complete a short personal project which creates a 20x20 table, printing a '#' where two numbers share a common factor above 1 (e.g. 2 and 8 share a common factor of 2, so that should show a hash). If no common factor is found, a '-' sign is printed instead.

Here is my (shortened to the appropriate bit) pseudo-code: REDACTED

The problem is that for some reason it prints too many '#' and '-' symbols, and then suddenly half the factors aren't correct.

What could be causing this? I have tried going through my code several times with no luck.


Solution

  • By the time you get to printing #, you're 3 loops deep. So instead of printing one # for each coordinate, you're printing a # for each match at each coordinate. E.g. (2,8) - matches at count==2, count==4, count==8.

    There's also the problem with the state variable reset that user1486477 pointed out.