Greatest Common Factor, Factors of a Number, and Juggling with List Comprehensions

It's always a good time, to open up a terminal and expressing calculations through code, just as any scientist would do, with the exception that I'm no scientist (at all), although I kind love Computer Science. I'm Software Developer so, it is expected, I guess.

Being from another country, speaking another language and having a different education at school when I was young, it feels a little bit different to read and identify mathematics content like Greatest Common Factor, Factors, and so on. Reading this article, I throught that would be nice to make some code that finds the factors of a number, and even better, the GCF from a list of numbers. I'm still wondering on what would be the best code, in terms of efficiency and with less time complexity, though.

Factors


Well, I started to perform a procedural code, 2 or 3 lines, but remembering how powerful are List Comprehensions (good source btw), many iterations and data strcutures can be performed with a single line.

Mission accomplished, with an easy and elegant code:


GCF (Greatest Common Factor) - 1° Round


This takes me back to my childhood, when I was 12, I guess.
Easy to put on a paper. To express the solution with code? Somewhat, at the beginning.
Here's the 1st approach, relying on the return of get_factors() function (list of factors).

Mission accomplished, but not meaningful (why using a list of lists of factors ?):


GCF (Greatest Common Factor) - 2° Round


No need of dealing with lists. It's just about numbers, just as you do on a paper.
A couple of variables were changed for the sake of readability, and the rest stills the same.
Mission accomplished and much better, isn't it?


Was an interesting task. It's a mix of childhood memories of mathematics from high school with my perspective nowadays as Software Developer, scratching the surface of Computer Science, but passionate on finding answers through programming languages, which in my case, is Python, most of the time.

I had fun today, indeed.

Thanks, Diary.

Mastodon