Jump to content

Factors of an integer: Difference between revisions

(Added zkl)
Line 349:
<pre>The factors of 45 are 1, 3, 5, 9, 15, 45
The factors of 12345 are 1, 3, 5, 15, 823, 2469, 4115, 12345</pre>
 
=={{header|bc}}==
<lang bc>/* Calculate the factors of n and return their count.
* This function mutates the global array f[] which will
* contain all factors of n in ascending order after the call!
*/
define f(n) {
auto i, d, h, h[], l, o
/* Local variables:
* i: Loop variable.
* d: Complementary (higher) factor to i.
* h: Will always point to the last element of h[].
* h[]: Array to hold the greater factor of the pair (x, y), where
* x * y == n. The factors are stored in descending order.
* l: Will always point to the next free spot in f[].
* o: For saving the value of scale.
*/
 
/* Use integer arithmetic */
o = scale
scale = 0
 
/* Two factors are 1 and n (if n != 1) */
f[l++] = 1
if (n == 1) return(1)
h[0] = n
 
/* Main loop */
for (i = 2; i < h[h]; i++) {
if (n % i == 0) {
d = n / i
if (d != i) {
h[++h] = d
}
f[l++] = i
}
}
 
/* Append the values in h[] to f[] */
while (h >= 0) {
f[l++] = h[h--]
}
 
scale = o
return(l)
}</lang>
 
=={{header|C}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.