2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
title: Factors of an integer
|
|
|
|
id: 597f1e7fbc206f0e9ba95dc4
|
|
|
|
challengeType: 5
|
2019-08-05 09:17:33 -07:00
|
|
|
forumTopicId: 302265
|
2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
|
|
|
|
## Description
|
|
|
|
<section id='description'>
|
2019-03-02 21:27:55 +09:00
|
|
|
Write a function that returns the factors of a positive integer as an array.
|
|
|
|
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
|
2018-09-30 23:01:58 +01:00
|
|
|
</section>
|
|
|
|
|
|
|
|
## Instructions
|
|
|
|
<section id='instructions'>
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Tests
|
|
|
|
<section id='tests'>
|
|
|
|
|
|
|
|
```yml
|
2018-10-04 14:37:37 +01:00
|
|
|
tests:
|
2019-11-20 07:01:31 -08:00
|
|
|
- text: <code>factors</code> should be a function.
|
2019-07-26 05:24:52 -07:00
|
|
|
testString: assert(typeof factors === 'function');
|
2018-10-20 21:02:47 +03:00
|
|
|
- text: <code>factors(45)</code> should return <code>[1,3,5,9,15,45]</code>.
|
2019-07-26 05:24:52 -07:00
|
|
|
testString: assert.deepEqual(factors(45), ans[0]);
|
2018-10-20 21:02:47 +03:00
|
|
|
- text: <code>factors(53)</code> should return <code>[1,53]</code>.
|
2019-07-26 05:24:52 -07:00
|
|
|
testString: assert.deepEqual(factors(53), ans[1]);
|
2018-10-20 21:02:47 +03:00
|
|
|
- text: <code>factors(64)</code> should return <code>[1,2,4,8,16,32,64]</code>.
|
2019-07-26 05:24:52 -07:00
|
|
|
testString: assert.deepEqual(factors(64), ans[2]);
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Challenge Seed
|
|
|
|
<section id='challengeSeed'>
|
|
|
|
|
|
|
|
<div id='js-seed'>
|
|
|
|
|
|
|
|
```js
|
2019-03-02 21:27:55 +09:00
|
|
|
function factors(num) {
|
2020-09-15 09:57:40 -07:00
|
|
|
|
2018-09-30 23:01:58 +01:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
### After Test
|
|
|
|
<div id='js-teardown'>
|
|
|
|
|
|
|
|
```js
|
2018-10-20 21:02:47 +03:00
|
|
|
const ans=[[1,3,5,9,15,45],[1,53],[1,2,4,8,16,32,64]];
|
2018-09-30 23:01:58 +01:00
|
|
|
```
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Solution
|
|
|
|
<section id='solution'>
|
|
|
|
|
|
|
|
|
|
|
|
```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;
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|