Last week someone ask me about calculating the largest divisor for a number within Power Apps. This had to be fast! With the right approach, this is easy to do.
Largest Divisor
Table of Contents
First I want to start by having a look at what the largest divisor is.
To calculate the largest divisor you need to look at a number and then divide is by other numbers.
So for example, if we look at the number 28. This can be divided by 2 and 7 as the following is true:
28 = 2*2*7
This now makes 7 the largest divisor of 28.
The important part of the solution here is to understand that all divisors are prime numbers (remember prime number you can only divide by 1 and themselves).
Largest Divisor in Power Apps
Now the first thought might be to create a flow, but that would be to slow for such a small thing. You wouldn’t want a user to wait for a few seconds.
Solving this problem in Power Apps means that we first need a list of prime numbers:
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293]
I’m opnly going to solve the problem up to 300. But of course you could increase the number of prime numbers to whatever you need.

Then I’m Filtering out the prime numbers that are smaller than our input number.
Set(varPrimes,Filter([2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293], Value <= Value(TextInput1.Text)));
Clear(colDivisors);
ForAll(varPrimes,
If(Mod(TextInput1.Text,ThisRecord.Value) = 0, Collect(colDivisors, ThisRecord.Value))
);
Then with a ForAll loop, we can step through the Prime numbers.
For each prime number we check using the Mod function, if we can divide the input by our prime number or not.
As we are stepping through the prime numbers in order the last prime number that we can divide our number by is the largest divisor.
Last(colDivisors).Value
Further optimize the solution
Now there is a further optimisation possible. This might be needed if we went up to higher numbers. As we are finding divisors We could recalculate the variable holding the Prime Numbers. By filtering out the larger numbers. But I will leave for a next time
Discover more from SharePains
Subscribe to get the latest posts sent to your email.
