August 29, 2024

Factor a Number with Power Query

Today I attempted to try the Excel BI Challenge #531 (Post | Feed | LinkedIn) but got sidetracked a little bit. I was able to figure out a piece of it that would be helpful for a Power Query extension I am working on: factoring a number.

For review, factoring a number is breaking down a number into all of the pairs of lesser/equal to numbers that can be multiplied together and make the larger number. Using the number ten (10) as an example, it would have the following factors: 1, 2, 5, 10. You can multiply 1 times 10 and get 10 while also multiplying 2 times 5.

The Code

Here is my code for this:

Here is a link to the gist: fnFactor.pq (github.com).

List.Generate() and records made this happen mostly. I looped through the number 1 until I reached the number being factored and used division to see if I got a whole number. In retrospect, I probably could have used Number.Mod() and checking if there was no remainder, but converting to text and finding a decimal (indicating there was a remainder) worked.

After making that check, a little cleanup was needed to get it into one distinct list and ordered.

Takeaways

List.Generate(), List.Accumulate, and scoping (@), probably with some other techniques I am forgetting as I write this, can be pretty helpful for loops. Mastering that, which I am still working on, is a good thing to learn when trying to solve complicated problems with Power Query.

You may also like