2018-09-30 22:01:58 +00:00
|
|
|
---
|
|
|
|
id: 597f1e7fbc206f0e9ba95dc4
|
2020-11-27 18:02:05 +00:00
|
|
|
title: Factors of an integer
|
2018-09-30 22:01:58 +00:00
|
|
|
challengeType: 5
|
2019-08-05 16:17:33 +00:00
|
|
|
forumTopicId: 302265
|
2021-01-13 02:31:00 +00:00
|
|
|
dashedName: factors-of-an-integer
|
2018-09-30 22:01:58 +00:00
|
|
|
---
|
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
# --description--
|
|
|
|
|
2019-03-02 12:27:55 +00:00
|
|
|
Write a function that returns the factors of a positive integer as an array.
|
2020-11-27 18:02:05 +00:00
|
|
|
|
2019-03-02 12:27:55 +00:00
|
|
|
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
# --hints--
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
`factors` should be a function.
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
```js
|
|
|
|
assert(typeof factors === 'function');
|
|
|
|
```
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
`factors(45)` should return `[1,3,5,9,15,45]`.
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
```js
|
|
|
|
assert.deepEqual(factors(45), ans[0]);
|
2018-09-30 22:01:58 +00:00
|
|
|
```
|
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
`factors(53)` should return `[1,53]`.
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
```js
|
|
|
|
assert.deepEqual(factors(53), ans[1]);
|
|
|
|
```
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
`factors(64)` should return `[1,2,4,8,16,32,64]`.
|
2018-09-30 22:01:58 +00:00
|
|
|
|
|
|
|
```js
|
2020-11-27 18:02:05 +00:00
|
|
|
assert.deepEqual(factors(64), ans[2]);
|
2018-09-30 22:01:58 +00:00
|
|
|
```
|
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
# --seed--
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
## --after-user-code--
|
2018-09-30 22:01:58 +00:00
|
|
|
|
|
|
|
```js
|
2018-10-20 18:02:47 +00:00
|
|
|
const ans=[[1,3,5,9,15,45],[1,53],[1,2,4,8,16,32,64]];
|
2018-09-30 22:01:58 +00:00
|
|
|
```
|
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
## --seed-contents--
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
```js
|
|
|
|
function factors(num) {
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
}
|
|
|
|
```
|
2018-09-30 22:01:58 +00:00
|
|
|
|
2020-11-27 18:02:05 +00:00
|
|
|
# --solutions--
|
2018-09-30 22:01:58 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
function factors(num)
|
|
|
|
{
|
|
|
|
let n_factors = [], i, sqr=Math.floor(Math.sqrt(num));
|
|
|
|
|
|
|
|
for (i = 1; i <=sqr ; i += 1)
|
|
|
|
if (num % i === 0)
|
|
|
|
{
|
|
|
|
n_factors.push(i);
|
|
|
|
if (num / i !== i)
|
|
|
|
n_factors.push(num / i);
|
|
|
|
}
|
|
|
|
n_factors.sort(function(a, b){return a - b;});
|
|
|
|
return n_factors;
|
|
|
|
}
|
|
|
|
```
|