mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-03-05 05:18:44 -05:00
chore(i18n): sync ukrainian translations (#49840
* chore: sync euler files * chore: sync ukrainian translations
This commit is contained in:
@@ -1,21 +1,22 @@
|
||||
---
|
||||
id: 61531b20cc9dfa2741a5b800
|
||||
title: College Algebra with Python Certification
|
||||
certification: college-algebra-with-python
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
-
|
||||
id: 63d83ff239c73468b059cd3f
|
||||
title: Multi-Function Calculator
|
||||
title: Build a Multi-Function Calculator
|
||||
-
|
||||
id: 63d83ffd39c73468b059cd40
|
||||
title: Graphing Calculator
|
||||
title: Build a Graphing Calculator
|
||||
-
|
||||
id: 63d8401039c73468b059cd41
|
||||
title: Three Math Games
|
||||
title: Build Three Math Games
|
||||
-
|
||||
id: 63d8401e39c73468b059cd42
|
||||
title: Financial Calculator
|
||||
title: Build a Financial Calculator
|
||||
-
|
||||
id: 63d8402e39c73468b059cd43
|
||||
title: Data Graph Explorer
|
||||
title: Build a Data Graph Explorer
|
||||
|
||||
@@ -11,13 +11,13 @@ dashedName: word-blanks
|
||||
|
||||
Вам надано речення з пропущеними словами: іменниками, дієсловами, прикметниками та прислівниками. Потім ви заповнюєте пропуски словами так, щоб завершене речення мало сенс.
|
||||
|
||||
Consider this sentence:
|
||||
Розглянемо це речення:
|
||||
|
||||
```md
|
||||
It was really ____, and we ____ ourselves ____.
|
||||
```
|
||||
|
||||
This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it. We can then assign the completed sentence to a variable as follows:
|
||||
У цьому реченні відсутні три слова: прикметник, дієслово та прислівник; ми можемо додати вибрані слова, щоб завершити речення. Потім ми можемо присвоїти завершене речення змінній наступним чином:
|
||||
|
||||
```js
|
||||
const sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";
|
||||
@@ -25,21 +25,21 @@ const sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselve
|
||||
|
||||
# --instructions--
|
||||
|
||||
In this challenge, we provide you with a noun, a verb, an adjective and an adverb. You need to form a complete sentence using words of your choice, along with the words we provide.
|
||||
У цьому завданні вам надано іменник, дієслово, прикметник та прислівник. Ви повинні завершити речення, використовуючи слова на власний вибір, а також надані нами.
|
||||
|
||||
You will need to use the string concatenation operator `+` to build a new string, using the provided variables: `myNoun`, `myAdjective`, `myVerb`, and `myAdverb`. You will then assign the formed string to the `wordBlanks` variable. You should not change the words assigned to the variables.
|
||||
Ви повинні використати оператор конкатенації `+`, щоб побудувати новий рядок, використовуючи надані змінні: `myNoun`, `myAdjective`, `myVerb` та `myAdverb`. Потім ви присвоїте сформований рядок до змінної `wordBlanks`. Ви не повинні змінювати слова, присвоєні зміннім.
|
||||
|
||||
You will also need to account for spaces in your string, so that the final sentence has spaces between all the words. The result should be a complete sentence.
|
||||
Вам також потрібно врахувати пропуски у рядку, щоб завершене речення містило пробіли між усіма словами. Результатом повинне бути завершене речення.
|
||||
|
||||
# --hints--
|
||||
|
||||
`wordBlanks` should be a string.
|
||||
`wordBlanks` має бути рядком.
|
||||
|
||||
```js
|
||||
assert(typeof wordBlanks === 'string');
|
||||
```
|
||||
|
||||
You should not change the values assigned to `myNoun`, `myVerb`, `myAdjective` or `myAdverb`.
|
||||
Ви не повинні змінювати значення, присвоєні до `myNoun`, `myVerb`, `myAdjective` або `myAdverb`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -50,7 +50,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should not directly use the values `dog`, `ran`, `big`, or `quickly` to create `wordBlanks`.
|
||||
Ви не повинні напряму використовувати значення `dog`, `ran`, `big` або `quickly`, щоб створити `wordBlanks`.
|
||||
|
||||
```js
|
||||
const newCode = removeAssignments(code);
|
||||
@@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`wordBlanks` should contain all of the words assigned to the variables `myNoun`, `myVerb`, `myAdjective` and `myAdverb` separated by non-word characters (and any additional words of your choice).
|
||||
`wordBlanks` має містити всі слова, присвоєні до змінних `myNoun`, `myVerb`, `myAdjective` та `myAdverb`, розділені розділовим знаком (та додаткові слова на ваш вибір).
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a3f503de51cf954ede28891d
|
||||
title: Знайдіть симетричну різницю множин
|
||||
title: Знайдіть симетричну різницю
|
||||
challengeType: 1
|
||||
forumTopicId: 301611
|
||||
dashedName: find-the-symmetric-difference
|
||||
@@ -8,13 +8,13 @@ dashedName: find-the-symmetric-difference
|
||||
|
||||
# --description--
|
||||
|
||||
Математичний термін <dfn>симетрична різниця двох множин</dfn> (`△` або `⊕`) – це множина елементів, які знаходяться в одній з множин, але не в обох. Наприклад, для множин `A = {1, 2, 3}` та `B = {2, 3, 4}`, `A △ B = {1, 4}`.
|
||||
Математичний термін <dfn>симетрична різниця двох множин</dfn> (`△` або `⊕`) — це множина елементів, які знаходяться в одній з множин, але не в обох. Наприклад, для множин `A = {1, 2, 3}` та `B = {2, 3, 4}`, `A △ B = {1, 4}`.
|
||||
|
||||
Симетрична різниця множин - це двійкова операція, тобто вона діє лише на два елементи. Тому, щоб оцінити вираз, який містить симетричну різницю множин серед *трьох* елементів(`A △ B △ C`), потрібно виконувати лише одну операцію одночасно. Таким чином, для множин `A` та `B` вище, і `C = {2, 3}`, `A △ B △ C = (A △ B) △ C = {1, 4} △ {2, 3} = {1, 2, 3, 4}`.
|
||||
Симетрична різниця — це двійкова операція, тобто вона працює лише з двома елементами. Тому, щоб оцінити вираз, який містить симетричну різницю множин серед *трьох* елементів (`A △ B △ C`), потрібно виконати лише одну операцію. Таким чином, для множин `A` та `B` вище, і `C = {2, 3}`, `A △ B △ C = (A △ B) △ C = {1, 4} △ {2, 3} = {1, 2, 3, 4}`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Створіть функцію, яка приймає два чи більше масиви, та повертає масив із їхньою симетричною різницею. Повернений масив має містити лише унікальні значення (* жодних дублікатів *).
|
||||
Створіть функцію, яка приймає два чи більше масиви, та повертає масив із їхньою симетричною різницею. Повернений масив повинен містити лише унікальні значення (*жодних дублікатів*).
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -54,7 +54,7 @@ assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5]);
|
||||
assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3);
|
||||
```
|
||||
|
||||
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` should return `[1, 4, 5]`.
|
||||
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` має повернути `[1, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5]);
|
||||
@@ -87,7 +87,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])` має містити лише п'ять елементів.
|
||||
`sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])` має містити лише п’ять елементів.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 61abc7ebf3029b56226de5b6
|
||||
title: Implement Binary Search
|
||||
title: Реалізуйте двійковий пошук
|
||||
challengeType: 1
|
||||
forumTopicId: 487618
|
||||
dashedName: implement-binary-search
|
||||
@@ -8,26 +8,26 @@ dashedName: implement-binary-search
|
||||
|
||||
# --description--
|
||||
|
||||
Binary search is an **O(log(n))** efficiency algorithm for searching a sorted array to find an element. It operates using the following steps:
|
||||
Двійковий пошук — це алгоритм для пошуку елемента у відсортованому масиві з ефективністю **O(log(n))**. Він працює за допомогою таких кроків:
|
||||
|
||||
1. Find the middle `value` of a sorted array. If `value == target` return `true` (The value has been found and the search is complete).
|
||||
1. If middle `value < target`, search right half of array in next compare.
|
||||
1. If middle `value > target`, search left half of array in next compare.
|
||||
1. If after searching the whole array the value is not present, return `false` (The array has been searched and the value is not in the array).
|
||||
1. Знайдіть середнє значення (`value`) відсортованого масиву. Якщо `value == target`, поверніть `true` (значення знайдено та пошук завершено).
|
||||
1. Якщо `value < target`, шукайте праву половину масиву під час наступного порівняння.
|
||||
1. Якщо `value > target`, шукайте ліву половину масиву під час наступного порівняння.
|
||||
1. Якщо після пошуку в усьому масиві значення відсутнє, поверніть `false` (в масиві було проведено пошук, а значення в масиві немає).
|
||||
|
||||
As you can see, you are successively halving an array, which gives you the log(n) efficiency. For this challenge, we want you to show your work - how you got to the target value... the path you took!
|
||||
Як бачите, ви послідовно ділите масив навпіл, що дає вам ефективність log(n). У цьому завданні ми хочемо, щоб ви показали свою роботу — як ви досягли цільового значення... шлях, який ви пройшли!
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function `binarySearch` that implements the binary search algorithm on an array, returning the path you took (each middle value comparison) to find the target in an array.
|
||||
Напишіть функцію `binarySearch`, яка реалізує алгоритм бінарного пошуку в масиві, повертаючи шлях, який ви обрали (порівняння кожного середнього значення), щоб знайти ціль в масиві.
|
||||
|
||||
The function takes a sorted array of integers and a target value as input. It returns an array containing (in-order) the middle value you found at each halving of the original array until you found the target value. The target value should be the last element of the returned array. If the value is not found, return the string `Value Not Found`.
|
||||
Функція приймає відсортований масив цілих чисел та цільове значення як ввід. Вона повертає масив, що містить (за порядком) середнє значення, яке ви знайшли при кожному діленні вихідного масиву навпіл, доки не знайдете цільове значення. Цільове значення повинне бути останнім елементом повернутого масиву. Якщо значення не знайдено, поверніть рядок `Value Not Found`.
|
||||
|
||||
For example, `binarySearch([1,2,3,4,5,6,7], 5)` would return `[4,6,5]`.
|
||||
Наприклад, `binarySearch([1,2,3,4,5,6,7], 5)` поверне `[4,6,5]`.
|
||||
|
||||
For this challenge, when halving, you MUST use `Math.floor()` when doing division: `Math.floor(x/2)`. This will give a consistent, testable path.
|
||||
При діленні навпіл у цьому завданні ОБОВ’ЯЗКОВО використайте `Math.floor()`: `Math.floor(x/2)`. Це дасть послідовний, перевірений шлях.
|
||||
|
||||
**Note:** The following array will be used in tests:
|
||||
**Примітка:** у тестах використовуватиметься цей масив:
|
||||
|
||||
```js
|
||||
const testArray = [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 8d5123c8c441eddfaeb5bdef
|
||||
title: Реалізація бульбашкового сортування
|
||||
title: Реалізуйте сортування бульбашкою
|
||||
challengeType: 1
|
||||
forumTopicId: 301612
|
||||
dashedName: implement-bubble-sort
|
||||
@@ -8,13 +8,13 @@ dashedName: implement-bubble-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Це перше із кількох завдань що стосуються алгоритмів сортування. Враховуючи масив несортованих елементів, ми хочемо повернути впорядкований масив. Ми побачимо кілька різних методів для цього і вивчимо певні компроміси між цими різними підходами. Хоча більшість сучасних мов мають вбудовані методи сортування для таких операцій, все ж важливо зрозуміти деякі загальні основні підходи та дізнатися, як їх можна здійснити.
|
||||
Це перше із декількох завдань, які стосуються алгоритмів сортування. Нам надано масив несортованих елементів, і нам потрібно повернути впорядкований масив. Ми побачимо кілька різних методів для цього і вивчимо певні компроміси між цими різними підходами. Хоча більшість сучасних мов мають вбудовані методи сортування для таких операцій, все ж важливо зрозуміти деякі загальні підходи та дізнатися, як їх можна реалізувати.
|
||||
|
||||
Тут ми розглянемо бульбашкове сортування. Метод бульбашкового сортування розпочинається на початку несортованого масиву і збільшує невідсортовані значення до кінця, повторюючи через масив поки він не буде повністю відсортованим. Це робиться шляхом порівняння суміжних елементів і їх заміни, якщо вони вийшли з ладу. Метод продовжує цикл по масиву, поки не відбудеться обмін, в якому масив буде відсортовано.
|
||||
Зараз ми розглянемо сортування бульбашкою. Метод сортування бульбашкою починається на початку несортованого масиву та перекидає несортовані значення в кінець, повторюючи масив, доки він не буде повністю відсортований. Це робиться шляхом порівняння суміжних елементів і їх заміни місцями, якщо вони не відповідають критеріям. Метод продовжує цикл, поки не відбудеться заміна місць та масив буде відсортовано.
|
||||
|
||||
Цей метод вимагає кількох ітерацій через масив, а для найгірших випадків має квадратичну складність часу. В той час як проста складність, як правило, непрактична у більшості ситуацій.
|
||||
Цей метод вимагає декількох ітерацій через масив, а в типових та найгірших ситуаціях має квадратичну часову складність. Простими словами, цей метод непрактичний у більшості випадків.
|
||||
|
||||
**Instructions:** Напишіть функцію `bubbleSort` яка приймає масив цілих чисел як введення і повертає масив цих цілих чисел у відсортованому порядку від найменшого до найбільшого.
|
||||
**Інструкція:** напишіть функцію `bubbleSort`, яка приймає масив цілих чисел як ввід та повертає масив цих цілих чисел у відсортованому порядку (від найменшого до найбільшого).
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -79,7 +79,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`bubbleSort` не повинен використовувати вбудований `.sort()` метод.
|
||||
`bubbleSort` не має використовувати вбудований метод `.sort()`.
|
||||
|
||||
```js
|
||||
assert(isBuiltInSortUsed());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8259367417b2b2512c86
|
||||
title: Реалізація сортування вставками
|
||||
title: Реалізуйте сортування включенням
|
||||
challengeType: 1
|
||||
forumTopicId: 301613
|
||||
dashedName: implement-insertion-sort
|
||||
@@ -8,9 +8,9 @@ dashedName: implement-insertion-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Наступний метод сортування, який ми розглянемо - це сортування вставками. Це метод створення відсортованого масиву на початку списку. Так, відсортований масив починається з першого елементу. Тоді йде перевірка наступного елемента і зміна його положення у відсортованому масиві, доки він не отримає відсортовану позицію. Після цього, список продовжує оновлюватися, а нові елементи стають на відсортовану позицію, аж поки сортування не завершиться. Цей алгоритм має квадратичну складність часу як у звичайних, так і у найгірших випадках.
|
||||
Наступний метод сортування, який ми розглянемо — це сортування включенням. Цей метод працює, створюючи відсортований масив на початку списку. Він починає відсортований масив з першого елементу. Потім він перевіряє наступний елемент і повертає його назад у відсортований масив, поки він не опиниться у потрібній позиції. Метод продовжує виконувати ітерацію та розташовувати нові елементи на потрібну позицію, поки не закінчаться елементи. Цей алгоритм має квадратичну часову складність у типових та найгірших випадках.
|
||||
|
||||
**Instructions:** Напишіть функцію `insertionSort`, де масив цілих чисел - це вхідні дані, і масив цих цілих чисел сортується від найменшого до найбільшого.
|
||||
**Інструкція:** напишіть функцію `insertionSort`, яка приймає масив цілих чисел як ввід та повертає масив цих цілих чисел у відсортованому порядку (від найменшого до найбільшого).
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -81,7 +81,7 @@ assert.sameMembers(
|
||||
assert.deepEqual(insertionSort([5, 4, 33, 2, 8]), [2, 4, 5, 8, 33])
|
||||
```
|
||||
|
||||
`insertionSort` не слід використовувати вбудований `.sort()` метод.
|
||||
`insertionSort` не має використовувати вбудований метод `.sort()`.
|
||||
|
||||
```js
|
||||
assert(isBuiltInSortUsed());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825c367417b2b2512c8f
|
||||
title: Реалізація сортування злиттям
|
||||
title: Реалізуйте сортування злиттям
|
||||
challengeType: 1
|
||||
forumTopicId: 301614
|
||||
dashedName: implement-merge-sort
|
||||
@@ -8,17 +8,17 @@ dashedName: implement-merge-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Ще один поширений алгоритм проміжного сортування - сортування злиттям. Як і швидке сортування, сортування злиттям також використовує метод розділяй і володарюй, рекурсивну методологію для сортування масиву. Він використовує перевагу в тому, що два масиви порівняно легко відсортувати, доки кожен з них відсортовано в першу чергу. Але ми почнемо тільки з одного масиву як з вхідного, то як же отримати з нього два відсортованих масиви? Ми можемо рекурсивно поділити початковий запис два, доки ми не досягнемо базового випадку масиву з одним предметом. Одноелементний масив природно відсортований, тому ми можемо почати комбінувати. Ця комбінація розгорне рекурсивні виклики, які розбивають оригінальний масив, врешті створюючи остаточний сортований масив усіх елементів. Кроки сортування злиттям:
|
||||
Ще один поширений алгоритм проміжного сортування — сортування злиттям. Як і швидке сортування, сортування злиттям також використовує принцип «Розділяй та володарюй», рекурсивну методологію для сортування масиву. Його перевага в тому, що два масиви порівняно легко відсортувати, якщо кожен з них вже відсортовано. Але ми почнемо тільки з одного масиву як з вхідного, то як же отримати з нього два відсортованих масиви? Ми можемо рекурсивно поділити початковий ввід на два, доки не досягнемо базового випадку масиву з одним елементом. Одноелементний масив вже відсортований, тому ми можемо почати комбінувати. Ця комбінація розгорне рекурсивні виклики, які розбивають початковий масив, врешті створюючи кінцевий відсортований масив з усіх елементів. Кроки сортування злиттям:
|
||||
|
||||
**1)** Рекурсивно розділити вхідний масив навпіл, поки підмасив лише з одним елементом не буде сформовано.
|
||||
|
||||
**2)** Об'єднати кожен сортований підмасив разом для створення остаточного сортованого масиву.
|
||||
**2)** Об’єднати кожен відсортований підмасив разом, щоб створити кінцевий відсортований масив.
|
||||
|
||||
Сортування злиттям є ефективним методом сортування зі складністю часу *O(nlog(n))*. Цей алгоритм популярний, оскільки він є продуктивним та відносно простим для реалізації.
|
||||
Сортування злиттям є ефективним методом сортування із часовою складністю *O(nlog(n))*. Цей алгоритм популярний, оскільки він є продуктивним та відносно простим для реалізації.
|
||||
|
||||
До речі, це буде останній алгоритм сортування, який ми тут висвітлюємо. Однак пізніше в розділі про деревовидні структури даних ми опишемо сортування по купі, ще один ефективний метод сортування, який вимагає двійкової купи у своїй реалізації.
|
||||
До речі, це буде останній алгоритм сортування, який ми висвітлюємо тут. Однак пізніше в розділі про деревовидні структури даних ми опишемо пірамідальне сортування — ще один ефективний метод сортування, який вимагає двійкової купи у своїй реалізації.
|
||||
|
||||
**Instructions:**Напишіть функцію `mergeSort` яка приймає масив цілих чисел як введення і повертає масив цих цілих чисел у відсортованому порядку від найменшого до найбільшого. Хороший спосіб реалізувати це - написати одну функцію, наприклад `merge`, яка відповідає за злиття двох сортованих масивів, та інша функція, наприклад, `mergeSort`, яка відповідає за рекурсію, що виробляє одноелементні масиви, для каналу на злиття. Успіхів!
|
||||
**Інструкція:** напишіть функцію `mergeSort`, яка приймає масив цілих чисел як ввід та повертає масив цих цілих чисел у відсортованому порядку (від найменшого до найбільшого). Хороший спосіб реалізувати це — написати одну функцію (наприклад, `merge`), яка відповідає за злиття двох відсортованих масивів, та ще одну функцію (наприклад, `mergeSort`), яка відповідає за рекурсію, що виробляє одноелементні масиви. Успіхів!
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -83,7 +83,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`mergeSort` не повинен використовувати вбудований `.sort()` метод.
|
||||
`mergeSort` не має використовувати вбудований метод `.sort()`.
|
||||
|
||||
```js
|
||||
assert(isBuiltInSortUsed());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825a367417b2b2512c89
|
||||
title: Реалізація швидкого сортування
|
||||
title: Реалізуйте швидке сортування
|
||||
challengeType: 1
|
||||
forumTopicId: 301615
|
||||
dashedName: implement-quick-sort
|
||||
@@ -8,11 +8,11 @@ dashedName: implement-quick-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Тут ми будемо рухатися до проміжного алгоритму сортування: швидке сортування. Швидке сортування - це ефективний, рекурсивний підхід "розподіляй і володарюй" у сортуванні масиву. В цьому методі, обираємо опорний елемент у вихідному масиві. Потім масив розділяється на два підмасиви із меншими і більшими значеннями ніж опорний елемент. Тоді ми об'єднуємо результат рекурсивного виклику алгоритму швидкого сортування в обидвох підмасивах. Це продовжується поки не буде досягнутий базовий регістр порожнього або єдиного елементу масиву, який ми повертаємо. Розмотування рекурсивних викликів повертає нам відсортований масив.
|
||||
Зараз ми перейдемо до проміжного алгоритму сортування: швидкого сортування. Швидке сортування — це ефективний рекурсивний підхід до сортування масиву «Розділяй та володарюй». У цьому методі вибирається опорне значення у вихідному масиві. Потім масив розділяється на два підмасиви зі значеннями, меншими і більшими за опорне значення. Потім ми об’єднуємо результат рекурсивного виклику алгоритму швидкого сортування в обидвох підмасивах. Це продовжується поки не буде досягнутий базовий випадок порожнього або єдиного елементу масиву, який ми повертаємо. Розмотування рекурсивних викликів повертає нам відсортований масив.
|
||||
|
||||
Швидке сортування є дуже ефективним методом, в середньому забезпечує *O(nlog(n))* продуктивність. Також це відносно легко реалізувати. Ці властивості роблять його популярним і корисним методом сортування.
|
||||
Швидке сортування є дуже ефективним методом, який в середньому забезпечує продуктивність *O(nlog(n))*. Також його відносно легко реалізувати. Ці властивості роблять його популярним і корисним методом сортування.
|
||||
|
||||
**Інструкція:** записати функцію `quickSort`, яка приймає на вхід масив цілих чисел і повертає відсортований масив цих цілих чисел від найменшого до найбільшого. Незважаючи на те, що вибір опорного елемента є важливим, тут підійде будь-яке значення для наших цілей. Щоб було простіше, то можна використати перший або останній елемент.
|
||||
**Інструкція:** напишіть функцію `quickSort`, яка приймає масив цілих чисел як ввід та повертає масив цих цілих чисел у відсортованому порядку (від найменшого до найбільшого). Попри те, що вибір опорного значення є важливим, для нашої мети підійде будь-яке значення. Щоб було простіше, то можна використати перший або останній елемент.
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -77,7 +77,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`quickSort` не повинен використовувати вбудований `.sort()` метод.
|
||||
`quickSort` не має використовувати вбудований метод `.sort()`.
|
||||
|
||||
```js
|
||||
assert(isBuiltInSortUsed());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8259367417b2b2512c85
|
||||
title: Реалізація сортування вибором
|
||||
title: Реалізуйте сортування вибором
|
||||
challengeType: 1
|
||||
forumTopicId: 301616
|
||||
dashedName: implement-selection-sort
|
||||
@@ -8,9 +8,9 @@ dashedName: implement-selection-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Тут ми виконаємо сортування вибором. Сортування вибором здійснюється шляхом вибору мінімального значення зі списку та його обміну з першим значенням у списку. Потім початок йде з другої позиції, обирається найменше значення з решти списку та здійснюється обмін цього значення з другим елементом. І такий процес обміну елементів продовжується, доки не дійдемо до кінця списку. Тепер список відсортовано. Сортування вибором завжди має квадратичну складність.
|
||||
Тут ми виконаємо сортування вибором. Сортування вибором вибирає мінімальне значення у списку та міняє його місцями з першим значенням у списку. Потім початок йде з другої позиції, обирається найменше значення з решти списку і він стає на місце другого елементу. Процес зміни місць продовжується, доки не дійдемо до кінця списку. Тепер список відсортовано. Сортування вибором завжди має квадратичну часову складність.
|
||||
|
||||
**Instructions**: Напишіть функцію `selectionSort`, де масив цілих чисел - це вхідні дані, і масив цих цілих чисел сортується від найменшого до найбільшого.
|
||||
**Інструкція:** напишіть функцію `selectionSort`, яка приймає масив цілих чисел як ввід та повертає масив цих цілих чисел у відсортованому порядку (від найменшого до найбільшого).
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -75,7 +75,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`selectionSort` не повинен використовувати вбудований `.sort()` метод.
|
||||
`selectionSort` не має використовувати вбудований метод `.sort()`.
|
||||
|
||||
```js
|
||||
assert(isBuiltInSortUsed());
|
||||
|
||||
@@ -8,7 +8,7 @@ dashedName: inventory-update
|
||||
|
||||
# --description--
|
||||
|
||||
Порівняйте та оновіть інвентар з масиву 2D та інший масив 2D на нові предмети. Оновіть поточну кількість предметів у інвентарі (у `arr1`). Якщо неможливо знайти об'єкт, додайте новий об'єкт та його кількість у масив інвентарю. Об'єкти висхідного масиву інвентарю мають бути в алфавітному порядку.
|
||||
Оновіть інвентар 2D-масиву, порівнявши його з іншим 2D-масивом свіжих поставок. Оновіть поточну кількість предметів інвентарю (в `arr1`). Якщо неможливо знайти предмет, додайте новий предмет та його кількість у масив інвентарю. Предмети поверненого масиву повинні бути в алфавітному порядку.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
@@ -8,9 +8,9 @@ dashedName: no-repeats-please
|
||||
|
||||
# --description--
|
||||
|
||||
Повертає кількість всіх перестановок заданого рядка, в яких не повторюються літери поспіль. Припустимо, що всі символи в заданому рядку унікальні.
|
||||
Поверніть кількість всіх перестановок заданого рядка, в яких не повторюються літери. Припустимо, що всі символи в заданому рядку унікальні.
|
||||
|
||||
Наприклад, `aab` повинен повернути 2, тому що загалом він має 6 перестановок (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), але тільки 2 з них ( `aba` та `aba`) не мають повторення однієї і тієї ж букви (в даному випадку `a`).
|
||||
Наприклад, `aab` має повертати 2, тому що загалом є 6 перестановок (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), але тільки 2 з них (`aba` та `aba`) не мають повторення однієї і тієї ж літери (в даному випадку `a`).
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -62,13 +62,13 @@ assert.strictEqual(permAlone('zzzzzzzz'), 0);
|
||||
assert.strictEqual(permAlone('a'), 1);
|
||||
```
|
||||
|
||||
`permAlone("aaab")` має повернути 0.
|
||||
`permAlone("aaab")` має повертати 0.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('aaab'), 0);
|
||||
```
|
||||
|
||||
`permAlone("aaabb")` має повернути 12.
|
||||
`permAlone("aaabb")` має повертати 12.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('aaabb'), 12);
|
||||
|
||||
@@ -8,11 +8,11 @@ dashedName: pairwise
|
||||
|
||||
# --description--
|
||||
|
||||
У масиві `arr`, знайдіть пари елементів, сума яких рівняється другому аргументу `arg` і поверніть суму їх індексів.
|
||||
Знайдіть пари елементів у масиві `arr`, сума яких дорівнює другому аргументу `arg` та поверніть суму їхніх індексів.
|
||||
|
||||
Ви можете використовувати декілька пар, які мають однакові числові елементи, але різні індекси. У кожній парі варто використовувати найнижчі доступні індекси. Після того, як елемент було використано, його вже не можна використати для пари з іншим елементом. Наприклад, `pairwise([1, 1, 2], 3)` створює пару `[2, 1]`, де 1 має індекс 0, а не 1, оскільки 0+2 < 1+2.
|
||||
Ви можете використовувати декілька пар, які мають однакові числові елементи, але різні індекси. У кожній парі варто використовувати найменші доступні індекси. Після того, як елемент було використано, його більше не можна використовувати для пари з іншим елементом. Наприклад, `pairwise([1, 1, 2], 3)` створює пару `[2, 1]`, де 1 має індекс 0, а не 1, оскільки 0+2 < 1+2.
|
||||
|
||||
Наприклад, `pairwise([7, 9, 11, 13, 15], 20)` повертає `6`. Пара з сумою 20 буде `[7, 13]` and `[9, 11]`. Тепер ми можемо записати масив з їхніми індексами і значеннями.
|
||||
Наприклад, `pairwise([7, 9, 11, 13, 15], 20)` повертає `6`. Парами з сумою 20 будуть `[7, 13]` та `[9, 11]`. Тепер ми можемо записати масив з їхніми індексами і значеннями.
|
||||
|
||||
<div style='margin-left: 2em;'>
|
||||
|
||||
@@ -22,13 +22,13 @@ dashedName: pairwise
|
||||
|
||||
</div>
|
||||
|
||||
Нижче ми беремо відповідні індекси і додаємо.
|
||||
Нижче ми візьмемо відповідні індекси і додамо їх.
|
||||
|
||||
<div style='margin-left: 2em;'>
|
||||
|
||||
7 + 13 = 20 → Індекси 0 + 3 = 3
|
||||
9 + 11 = 20 → Індекси 1 + 2 = 3
|
||||
3 + 3 = 6 → Повертає `6`
|
||||
9 + 11 = 20 → індекси 1 + 2 = 3
|
||||
3 + 3 = 6 → Повернути `6`
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a5d02bd919fcf9ca8cf46cb
|
||||
title: Створіть додаток Light-Bright
|
||||
title: Створіть додаток «Light-Bright»
|
||||
challengeType: 3
|
||||
forumTopicId: 302350
|
||||
dashedName: build-a-light-bright-app
|
||||
@@ -8,23 +8,23 @@ dashedName: build-a-light-bright-app
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <https://codepen.io/freeCodeCamp/full/eyLYXE>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <https://codepen.io/freeCodeCamp/full/eyLYXE>.
|
||||
|
||||
**Правило #1: ** Не дивіться на зразок коду проєкту. Визначте його самі.
|
||||
**Правило №1:** не дивіться на код проєкту в прикладі. Напишіть його власноруч.
|
||||
|
||||
**Правило №2:** виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
** Історія користувача: ** Я можу натискати чи перетягувати курсор миші, щоб зафарбувати кружечки.
|
||||
**Історія користувача:** я можу натискати чи перетягувати курсор миші, щоб зафарбувати кружечки.
|
||||
|
||||
** Історія користувача:** При подвійному натисканні на зафарбований кружечок я можу видалити колір.
|
||||
**Історія користувача:** я можу двічі натиснути на зафарбований кружечок, щоб видалити колір.
|
||||
|
||||
**Історія користувача: ** Я можу натиснути на зафарбований кружечок, щоб змінити його колір.
|
||||
**Історія користувача:** я можу натиснути на зафарбований кружечок, щоб змінити колір.
|
||||
|
||||
** Історія користувача: ** Мені потрібно отримати кружечок іншого кольору при кожному натисканні.
|
||||
**Історія користувача:** я отримую кружечок іншого кольору при кожному натисканні.
|
||||
|
||||
** Історія користувача: ** Я можу натиснути на кнопку "Скинути", щоб видалити останній колір.
|
||||
**Історія користувача:** я можу натиснути на кнопку «Reset», щоб видалити останній колір.
|
||||
|
||||
** Історія користувача: ** Я можу натиснути на кнопку "Скинути все", щоб видалити кольори з усіх зафарбованих кружечків.
|
||||
**Історія користувача:** я можу натиснути на кнопку «Reset All», щоб видалити всі кольори.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -12,17 +12,17 @@ dashedName: build-a-nightlife-coordination-app
|
||||
|
||||
Тут наведено конкретні історії користувача, які варто імплементувати в даний проєкт:
|
||||
|
||||
**User Story:** As an unauthenticated user, you can view all bars in your area.
|
||||
**Історія користувача:** як неавторизований користувач, ви можете переглянути всі бари неподалік.
|
||||
|
||||
**User Story:** As an authenticated user, you can add yourself to a bar to indicate you are going there tonight.
|
||||
**Історія користувача:** як неавторизований користувач, ви можете додати себе в бар, щоб вказати, що ви збираєтесь туди ввечері.
|
||||
|
||||
**User Story:** As an authenticated user, you can remove yourself from a bar if you no longer want to go there.
|
||||
**Історія користувача:** як неавторизований користувач, ви можете видалити себе з бару, якщо ви більше не хочете туди йти.
|
||||
|
||||
**Історія користувача:** Як неавторизований користувач, коли ви входите в систему, вам не треба виконувати пошук знову.
|
||||
**Історія користувача:** як неавторизований користувач, коли ви входите в систему, вам не потрібно виконувати пошук знову.
|
||||
|
||||
**Hint:** Try using the Yelp API to find venues in the cities your users search for. Якщо ви використовуєте Yelp API, не забудьте вказати це у вашому додатку.
|
||||
**Підказка:** спробуйте використати Yelp API, щоб знайти заклади в містах, які шукають ваші користувачі. Якщо ви використовуєте Yelp API, не забудьте вказати це у вашому додатку.
|
||||
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Then submit the URL to it in the Solution Link field. Optionally, also submit a link to your project's source code in the GitHub Link field.
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Потім введіть URL-адресу проєкту в полі «Посилання на рішення». За бажанням введіть посилання на початковий код проєкту в полі «Посилання на GitHub».
|
||||
|
||||
# --solutions--
|
||||
|
||||
|
||||
@@ -8,25 +8,25 @@ dashedName: build-a-pinterest-clone
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://build-a-pinterest-clone.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://build-a-pinterest-clone.freecodecamp.rocks/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://build-a-pinterest-clone.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://build-a-pinterest-clone.freecodecamp.rocks/</a>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Як неавторизований користувач, я можу увійти за допомогою GitHub.
|
||||
**Історія користувача:** як неавторизований користувач, я можу увійти за допомогою GitHub.
|
||||
|
||||
** Історія користувача: ** Як авторизований користувач, я можу посилатися на зображення.
|
||||
**Історія користувача:** як авторизований користувач, я можу посилатися на зображення.
|
||||
|
||||
** Історія користувача: ** Як авторизований користувач, я можу видаляти зображення на які я розміщував посилання.
|
||||
**Історія користувача:** як авторизований користувач, я можу видаляти зображення, на які я розміщував(-ла) посилання.
|
||||
|
||||
**Історія користувача: ** Як авторизований користувач, я можу бачити стінку в стилі Pinterest з усіма зображеннями, на які я посилався.
|
||||
**Історія користувача:** як авторизований користувач, я можу бачити стіну в стилі Pinterest з усіма зображеннями, на які я посилався(-лась).
|
||||
|
||||
**Історія користувача:** Як неавторизований користувач, я можу переглядати стінки з зображеннями інших користувачів.
|
||||
**Історія користувача:** як неавторизований користувач, я можу переглядати стіни з зображеннями інших користувачів.
|
||||
|
||||
**Історія користувача:** Як авторизований користувач, якщо я завантажу неробоче зображення, то отримаю в результаті його заміну на зображення-заповнювач. (Ви можете скористатися детектором зламаних зображень jQuery)
|
||||
**Історія користувача:** як авторизований користувач, якщо я завантажу зламане зображення, його замінять на зображення-заповнювач. (Ви можете скористатися детектором зламаних зображень jQuery)
|
||||
|
||||
**Hint:** Masonry.js is a library that allows for Pinterest-style image grids.
|
||||
**Підказка:** Masonry.js — це бібліотека, яка дозволяє створювати сітки зображень у стилі Pinterest.
|
||||
|
||||
Як тільки ви завершите імплементацію цих історій користувача, введіть URL-адресу вашого онлайн додатку і, за бажанням, вашого GitHub репозиторію. Тоді натисніть кнопку "Я завершив це завдання".
|
||||
Як тільки ви виконаєте історії користувачів, введіть URL-адресу вашого застосунку і, за бажанням, вашого репозиторію на GitHub. Потім натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
Ви можете отримати фідбек до свого проєкту, поділившись ним на <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">форумі freeCodeCamp</a>.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a4b7fcdb66f799f199e11db
|
||||
title: Створіть гру Pong
|
||||
title: Створіть гру «Pong»
|
||||
challengeType: 3
|
||||
forumTopicId: 302353
|
||||
dashedName: build-a-pong-game
|
||||
@@ -8,19 +8,19 @@ dashedName: build-a-pong-game
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <https://codepen.io/satyamdev/full/pdMmBp>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <https://codepen.io/satyamdev/full/pdMmBp>.
|
||||
|
||||
**Правило #1: ** Не дивіться на зразок коду проєкту. Визначте його самі.
|
||||
**Правило №1:** не дивіться на код проєкту в прикладі. Напишіть його власноруч.
|
||||
|
||||
**Правило №2:** виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Я можу керувати ігровою лопаткою.
|
||||
**Історія користувача:** я можу керувати ігровою лопаткою.
|
||||
|
||||
** Історія користувача:** Комп'ютер може керувати іншою ігровою лопаткою.
|
||||
**Історія користувача:** комп’ютер може керувати іншою ігровою лопаткою.
|
||||
|
||||
**Історія користувача:** Контролер комп'ютера непереможний. Він в жодному випадку не повинен пропустити м'яч.
|
||||
**Історія користувача:** контролер комп’ютера непереможний. Він в жодному випадку не повинен пропустити м’яч.
|
||||
|
||||
**Історія користувача:** Гра відстежує рахунок гравця та комп'ютера.
|
||||
**Історія користувача:** гра відстежує рахунок гравця та комп’ютера.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -8,23 +8,23 @@ dashedName: build-a-recipe-box
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/dNVazZ/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/dNVazZ/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/dNVazZ/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/dNVazZ/</a>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Я можу створювати рецепти, в яких є назви та інгредієнти.
|
||||
**Історія користувача:** я можу створювати рецепти, які мають назви та інгредієнти.
|
||||
|
||||
**Історія користувача:** Я можу побачити показ індексів, де видно назви всіх рецептів.
|
||||
**Історія користувача:** я можу побачити показ індексів, де видно назви всіх рецептів.
|
||||
|
||||
**Історія користувача:** Я можу натиснути на будь-який з цих рецептів для його перегляду.
|
||||
**Історія користувача:** я можу натиснути на будь-який рецепт, щоб переглянути його.
|
||||
|
||||
**Історія користувача:** Я можу редагувати ці рецепти.
|
||||
**Історія користувача:** я можу редагувати рецепти.
|
||||
|
||||
**Історія користувача: ** Я можу видаляти ці рецепти.
|
||||
**Історія користувача:** я можу видаляти рецепти.
|
||||
|
||||
**Історія користувача:** Всі нові рецепти, які я додаю, зберігаються в локальному сховищі браузера. Якщо я оновлю сторінку, ці рецепти все ще будуть там.
|
||||
**Історія користувача:** усі нові рецепти, які я додаю, зберігаються в локальному сховищі браузера. Якщо я оновлю сторінку, рецепти досі будуть там.
|
||||
|
||||
**Підказка:** Вам слід вказувати префікс локальних ключів зберігання на CodePen, а саме - `_username_recipes`
|
||||
**Підказка:** вам потрібно вказувати префікс ключів локального сховища на CodePen, тобто `_username_recipes`
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7153d8c242eddfaeb5bd13
|
||||
title: Створіть гру Roguelike Dungeon Crawler
|
||||
title: Створіть мандрівну гру «Dungeon Crawler»
|
||||
challengeType: 3
|
||||
forumTopicId: 302355
|
||||
dashedName: build-a-roguelike-dungeon-crawler-game
|
||||
@@ -8,27 +8,27 @@ dashedName: build-a-roguelike-dungeon-crawler-game
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/apLXEJ/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/apLXEJ/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/apLXEJ/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/apLXEJ/</a>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні Вам бібліотеки або API. Оформте за власним стилем.
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** у мене є здоров'я, рівень і зброя. Я можу підібрати кращу зброю. Я можу підбирати ліки.
|
||||
**Історія користувача:** я маю здоров’я, рівень і зброю. Я можу підібрати кращу зброю. Я можу підбирати ліки.
|
||||
|
||||
**Історія користувача:** Усі предмети та вороги розташовані на карті навмання.
|
||||
**Історія користувача:** усі предмети та вороги розташовані на карті випадково.
|
||||
|
||||
**Історія користувача:** Я можу пересуватися по карті, натикаючись на об'єкти.
|
||||
**Історія користувача:** я можу пересуватися по карті, натикаючись на об’єкти.
|
||||
|
||||
**Історія користувача:** Я можу скрізь ходити у межах кордонів карти, але не можу оминути ворога, доки його не здолаю.
|
||||
**Історія користувача:** я можу ходити будь-де у межах кордонів карти, але не можу оминути ворога, доки не здолаю його.
|
||||
|
||||
**Історія користувача:** Значна територія карти прихована. Коли я рухаюсь, мені відкривається новий простір, доступний на певній відстані від мене.
|
||||
**Історія користувача:** значна територія карти прихована. Коли я рухаюсь, мені відкривається новий простір, доступний на певній відстані від мене.
|
||||
|
||||
**Історія користувача:** Коли я вбиваю ворога, він зникає і мені нараховуються очки досвіду, необхідні для підвищення рівня.
|
||||
**Історія користувача:** коли я вбиваю ворога, він зникає і мені нараховуються очки досвіду, необхідні для підвищення рівня.
|
||||
|
||||
**Історія користувача:** У поєдинку з ворогом ми по черзі завдаємо удар один одному, доки хтось з нас не програє. Сила моєї атаки залежить від мого рівня та виду зброї. Сила атаки ворога залежить від його рівня. Сила шкоди визначається випадково у межах певного діапазону.
|
||||
**Історія користувача:** у поєдинку з ворогом ми по черзі завдаємо удар один одному, доки хтось з нас не програє. Сила моєї атаки залежить від мого рівня та виду зброї. Сила атаки ворога залежить від його рівня. Сила шкоди визначається випадково у межах певного діапазону.
|
||||
|
||||
**Історія користувача:** Дійшовши до боса та здолавши його, я одержую перемогу.
|
||||
**Історія користувача:** я отримую перемогу, дійшовши до боса та здолавши його.
|
||||
|
||||
**Історія користувача:** Гра має бути складною, але залишати шанс на перемогу.
|
||||
**Історія користувача:** гра повинна бути складною, але її можливо виграти.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7158d8c442eddfaeb5bd1c
|
||||
title: Розробіть гру "Саймон"
|
||||
title: Створіть гру «Simon»
|
||||
challengeType: 3
|
||||
forumTopicId: 302357
|
||||
dashedName: build-a-simon-game
|
||||
@@ -8,27 +8,27 @@ dashedName: build-a-simon-game
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/obYBjE" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/obYBjE</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/obYBjE" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/obYBjE</a>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Я починаю випадковим чином натискати на кнопки.
|
||||
**Історія користувача:** мені надається послідовність випадково натиснутих кнопок.
|
||||
|
||||
**Історія користувача:** Кожен раз коли я у правильній послідовності натискаю на кнопки, то бачу число з кількістю виконаних натисків, але з додатковим кроком.
|
||||
**Історія користувача:** кожного разу, коли я натискаю на кнопки у правильній послідовності, то бачу ту ж саму послідовність кнопок, але на одну більше.
|
||||
|
||||
**Історія користувача:** Я чую звуки кожної кнопки, коли у грі працює певна їхня послідовність і тоді, коли я сам натискаю на кнопку.
|
||||
**Історія користувача:** я чую звуки кожної кнопки, коли у грі працює певна їхня послідовність і тоді, коли я натискаю на них власноруч.
|
||||
|
||||
**Історія користувача: ** Якщо я натискаю на хибну кнопку, то я це помічаю і дана послідовність натиснутих кнопок починає знову нагадувати мені найпершу із них, тому я можу спробувати зіграти знову.
|
||||
**Історія користувача: ** якщо я натискаю на неправильну кнопку, мене повідомляють і дана послідовність повторюється, щоб спробувати знову.
|
||||
|
||||
**Історія користувача:** Я можу побачити скільки кроків є в даній послідовності натиснутих кнопок.
|
||||
**Історія користувача:** я можу бачити кількість кроків у даній послідовності кнопок.
|
||||
|
||||
**Історія користувача:** Якщо я захочу зіграти наново, то я можу натиснути кнопку, яка за це відповідає і тоді гра поверне мене до першого кроку.
|
||||
**Історія користувача:** якщо я хочу зіграти спочатку, то я можу натиснути відповідну кнопку і тоді гра почнеться з першого кроку.
|
||||
|
||||
**Історія користувача:** Я можу грати у строгому режимі, там де при моєму натиснені на хибну клавішу, програма повідомляє мені, що я помилився і гра починається заново з іншою послідовністю натиснутих кнопок.
|
||||
**Історія користувача:** я можу грати у строгому режимі, де при натисканні на неправильну клавішу мене повідомляють та гра починається спочатку з випадковою послідовністю кнопок.
|
||||
|
||||
**Історія користувача:** Я можу виграти гру, набравши 20 правильних послідовних кроків. Мене повідомляють про мою перемогу і тоді гра починається спочатку.
|
||||
**Історія користувача:** я можу виграти гру, набравши 20 правильних послідовних кроків. Мене повідомляють про мою перемогу і тоді гра починається спочатку.
|
||||
|
||||
**Підказка:** Тут є mp3 файли, які ви можете використати для кожної кнопки: `https://s3.amazonaws.com/freecodecamp/simonSound1.mp3`, `https://s3.amazonaws.com/freecodecamp/simonSound2.mp3`, `https://s3.amazonaws.com/freecodecamp/simonSound3.mp3`, `https://s3.amazonaws.com/freecodecamp/simonSound4.mp3`.
|
||||
**Підказка:** ось mp3, які ви можете використати для кожної кнопки: `https://s3.amazonaws.com/freecodecamp/simonSound1.mp3`, `https://s3.amazonaws.com/freecodecamp/simonSound2.mp3`, `https://s3.amazonaws.com/freecodecamp/simonSound3.mp3`, `https://s3.amazonaws.com/freecodecamp/simonSound4.mp3`.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7158d8c442eedfaeb5bd1c
|
||||
title: Створіть гру Хрестики-нулики
|
||||
title: Створіть гру «Хрестики-нулики»
|
||||
challengeType: 3
|
||||
forumTopicId: 302358
|
||||
dashedName: build-a-tic-tac-toe-game
|
||||
@@ -8,15 +8,15 @@ dashedName: build-a-tic-tac-toe-game
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/KzXQgy/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/KzXQgy/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/KzXQgy/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/KzXQgy/</a>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Я можу грати в Хрестики-нулики за допомогою комп'ютера.
|
||||
**Історія користувача:** я можу грати в хрестики-нулики з комп’ютером.
|
||||
|
||||
**Історія користувача:** Моя гра по закінченню буде скинута, тож я зможу грати з самого початку.
|
||||
**Історія користувача:** моя гра по закінченню буде скинута, тому я зможу грати знову.
|
||||
|
||||
**Історія користувача:** Я можу робити вибір, чи я хочу грати як X чи O.
|
||||
**Історія користувача:** я можу вибирати між X та O.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -12,23 +12,23 @@ dashedName: build-a-voting-app
|
||||
|
||||
Тут наведено конкретні історії користувача, які варто імплементувати в даний проєкт:
|
||||
|
||||
**Історія користувача:** Як авторизований користувач, ви можете зберігати свої опитування та повертатися до них пізніше.
|
||||
**Історія користувача:** як авторизований користувач, ви можете зберігати свої опитування та повертатися до них пізніше.
|
||||
|
||||
** Історія користувача:** Як авторизований користувач, ви можете ділитися опитуваннями з своїми друзями.
|
||||
** Історія користувача:** як авторизований користувач, ви можете ділитися опитуваннями зі своїми друзями.
|
||||
|
||||
**Історія користувача: ** Як авторизований користувач, ви можете бачити сукупні результати своїх опитувань.
|
||||
**Історія користувача: ** як авторизований користувач, ви можете бачити результати своїх опитувань.
|
||||
|
||||
**Історія користувача:** Як авторизований користувач, ви можете видаляти опитування, які більше для вас не є актуальними.
|
||||
**Історія користувача:** як авторизований користувач, ви можете видаляти опитування.
|
||||
|
||||
**Історія користувача: **Як авторизований користувач, ви можете створювати опитування з будь-якою кількістю можливих елементів.
|
||||
**Історія користувача:** як авторизований користувач, ви можете створювати опитування з будь-якою кількістю можливих елементів.
|
||||
|
||||
**Історія користувача:** Як неавторизований чи авторизований користувач, ви можете бачити та приймати участь в опитуваннях інших користувачів.
|
||||
**Історія користувача:** як неавторизований чи авторизований користувач, ви можете бачити опитування інших користувачів та брати в них участь.
|
||||
|
||||
**Історія користувача: **Як неавторизований чи авторизований користувач, ви можете бачити результати опитування у формі діаграми. (Це може бути реалізовано за допомогою Chart.js або Google Charts.)
|
||||
**Історія користувача: ** як неавторизований чи авторизований користувач, ви можете бачити результати опитування у вигляді діаграми. (Це може бути реалізовано за допомогою Chart.js або Google Charts.)
|
||||
|
||||
**Історія користувача: **Як авторизований користувач, ви можете створити нову опцію в опитуванні, якщо вам не подобаються наявні.
|
||||
**Історія користувача: ** як авторизований користувач, ви можете створити нову опцію в опитуванні, якщо вам не подобаються наявні.
|
||||
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Then submit the URL to it in the Solution Link field. Optionally, also submit a link to your project's source code in the GitHub Link field.
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Потім введіть URL-адресу проєкту в полі «Посилання на рішення». За бажанням введіть посилання на початковий код проєкту в полі «Посилання на GitHub».
|
||||
|
||||
# --solutions--
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7158d8c442eddfaeb5bd19
|
||||
title: Створіть переглядач Вікіпедії
|
||||
title: Створіть переглядач вікіпедії
|
||||
challengeType: 3
|
||||
forumTopicId: 302360
|
||||
dashedName: build-a-wikipedia-viewer
|
||||
@@ -8,17 +8,17 @@ dashedName: build-a-wikipedia-viewer
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/wGqEga/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/wGqEga/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/wGqEga/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/wGqEga/</a>.
|
||||
|
||||
The MediaWiki software powers Wikipedia, and it helps you collect and organize knowledge and make it available to people.
|
||||
Вікіпедія працює завдяки програмному забезпеченню MediaWiki, а це допомагає збирати й систематизувати інформацію та робити її доступною для людей.
|
||||
|
||||
Using the MediaWiki API, replicate the search function and random article function, similar to the example app above. You can use Wikipedia as your data source.
|
||||
Використовуючи API MediaWiki, відтворіть функцію пошуку та функцію випадкової статті, подібно до прикладу застосунку вище. Ви можете використовувати вікіпедію як джерело даних.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**User Story:** I can search Wikipedia entries in a search box and see the resulting Wikipedia entries.
|
||||
**Історія користувача:** я можу здійснювати пошук у вікіпедії за допомогою пошукового поля та бачити статті, що відповідають запиту.
|
||||
|
||||
**User Story:** I can click a button to see a random Wikipedia entry.
|
||||
**Історія користувача:** я можу натиснути кнопку, щоб побачити випадкову статтю у вікіпедії.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -8,17 +8,17 @@ dashedName: build-an-image-search-abstraction-layer
|
||||
|
||||
# --description--
|
||||
|
||||
Build a full stack JavaScript app that allows you to search for images like this: <a href="https://image-search-abstraction-layer.freecodecamp.rocks/query/lolcats%20funny?page=10" target="_blank" rel="noopener noreferrer nofollow">https://image-search-abstraction-layer.freecodecamp.rocks/query/lolcats%20funny?page=10</a> and browse recent search queries like this: <a href="https://image-search-abstraction-layer.freecodecamp.rocks/recent/" target="_blank" rel="noopener noreferrer nofollow">https://image-search-abstraction-layer.freecodecamp.rocks/recent/</a>. Для виконання проєкту використайте конструктор сайту на власний вибір.
|
||||
Створіть повний пакет додатку JavaScript, який дозволяє шукати зображення, схоже до цього: <a href="https://image-search-abstraction-layer.freecodecamp.rocks/query/lolcats%20funny?page=10" target="_blank" rel="noopener noreferrer nofollow">https://image-search-abstraction-layer.freecodecamp.rocks/query/lolcats%20funny?page=10</a> та переглядати останні пошукові запити, схоже до цього: <a href="https://image-search-abstraction-layer.freecodecamp.rocks/recent/" target="_blank" rel="noopener noreferrer nofollow">https://image-search-abstraction-layer.freecodecamp.rocks/recent/</a>. Для виконання проєкту використайте конструктор сайту на власний вибір.
|
||||
|
||||
Тут наведено конкретні історії користувача, які варто реалізувати в даному проєкті:
|
||||
Тут наведено конкретні історії користувача, які варто імплементувати в даний проєкт:
|
||||
|
||||
**Історія користувача:** Ви можете отримати посилання на зображення, опис та посилання на сторінки для набору зображень, що стосуються заданого пошукового рядка.
|
||||
**Історія користувача:** ви можете отримати посилання на зображення, опис та посилання на сторінки для набору зображень, що стосуються заданого пошукового рядка.
|
||||
|
||||
**Історія користувача:** Ви можете нумерувати відповіді, додавши до посилання параметр `?page=2`.
|
||||
**Історія користувача:** ви можете нумерувати відповіді, додавши до посилання параметр `?page=2`.
|
||||
|
||||
**Історія користувача:** Ви можете отримати список останніх пошукових рядків.
|
||||
**Історія користувача:** ви можете отримати список останніх пошукових рядків.
|
||||
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Then submit the URL to it in the Solution Link field. Optionally, also submit a link to your project's source code in the GitHub Link field.
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Потім введіть URL-адресу проєкту в полі «Посилання на рішення». За бажанням введіть посилання на початковий код проєкту в полі «Посилання на GitHub».
|
||||
|
||||
# --solutions--
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7154d8c242eddfaeb5bd13
|
||||
title: Створіть гру Життя
|
||||
title: Створіть гру «Життя»
|
||||
challengeType: 3
|
||||
forumTopicId: 302362
|
||||
dashedName: build-the-game-of-life
|
||||
@@ -8,34 +8,34 @@ dashedName: build-the-game-of-life
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/BpwMZv/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/BpwMZv/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/BpwMZv/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/BpwMZv/</a>.
|
||||
|
||||
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway. It is a <em>zero-player game</em>, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
|
||||
Гра життя — це клітинний автомат, розроблений британським математиком Джоном Хортоном Конвеєм. Це <em>гра з нульовим гравцем</em>, тобто її розвиток визначається початковим станом та не потребує подальших вводів. Людина взаємодіє з грою, створюючи початкову конфігурацію та спостерігаючи за розвитком.
|
||||
|
||||
The universe of the Game of Life is an infinite, two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, populated and unpopulated. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent.
|
||||
Всесвіт гри — це нескінченна двовимірна ортогональна сітка квадратних клітинок, кожна з яких перебуває в одному з двох можливих станів: заселеному та незаселеному. Кожна клітинка взаємодіє зі своїми вісьмома сусідами, які є клітинками, розташованими по горизонталі, вертикалі або діагоналі.
|
||||
|
||||
At each step in time, the following transitions occur:
|
||||
На кожному кроці в часі відбуваються такі переходи:
|
||||
|
||||
- Any live cell with fewer than two live neighbours dies, as if by underpopulation.
|
||||
- Any live cell with two or three live neighbours lives on to the next generation.
|
||||
- Any live cell with more than three live neighbours dies, as if by overpopulation.
|
||||
- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
|
||||
- Будь-яка жива клітинка з менш ніж двома живими сусідами гине від недостатнього заселення.
|
||||
- Будь-яка жива клітинка з двома чи трьома живими сусідами живе до наступного покоління.
|
||||
- Будь-яка жива клітинка з більш ніж трьома живими сусідами гине від перенаселення.
|
||||
- Будь-яка мертва клітинка з трьома живими сусідами стає живою клітинкою шляхом репродукції.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**User Story:** When I first arrive at the game, it will randomly generate a board and start playing.
|
||||
**Історія користувача:** коли я вперше заходжу в гру, вона випадково створить площину і почне гру.
|
||||
|
||||
**User Story:** I can start and stop the board.
|
||||
**Історія користувача:** я можу запустити і зупинити площину.
|
||||
|
||||
**User Story:** I can set up the board.
|
||||
**Історія користувача:** я можу налаштувати площину.
|
||||
|
||||
**User Story:** I can clear the board.
|
||||
**Історія користувача:** я можу очистити площину.
|
||||
|
||||
**User Story:** When I press start, the game will play out.
|
||||
**Історія користувача:** коли я натисну кнопку «Start», гра почнеться.
|
||||
|
||||
**User Story:** Each time the board changes, I can see how many generations have gone by.
|
||||
**Історія користувача:** щоразу, коли змінюється площина, я можу побачити, скільки поколінь минуло.
|
||||
|
||||
When you are finished, include a link to your project and click the "I've completed this challenge" button.
|
||||
Коли закінчите, надайте посилання на свій проєкт та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
Ви можете отримати фідбек до свого проєкту, поділившись ним на <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">форумі freeCodeCamp</a>.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7158d8c443eddfaeb5bd0e
|
||||
title: Створюйте діаграму фондової біржі
|
||||
title: Створіть діаграму фондової біржі
|
||||
challengeType: 4
|
||||
forumTopicId: 302363
|
||||
dashedName: chart-the-stock-market
|
||||
@@ -12,15 +12,15 @@ dashedName: chart-the-stock-market
|
||||
|
||||
Тут наведено конкретні історії користувача, які варто імплементувати в даний проєкт:
|
||||
|
||||
**Історія користувача:** Ви можете переглянути графік, що відображає останні лінії трендів на кожні додані акції.
|
||||
**Історія користувача:** ви можете переглянути графік, який зображає останні тренди для кожної доданої акції.
|
||||
|
||||
**Історія користувача:** Ви можете додати нові акції за назвою їх символу.
|
||||
**Історія користувача:** ви можете додати нові акції за назвою їхнього символу.
|
||||
|
||||
**Історія користувача:** Ви можете видалити акції.
|
||||
**Історія користувача:** ви можете видалити акції.
|
||||
|
||||
**Історія користувача:** Ви можете бачити зміни в режимі реального часу, коли будь-який інший користувач додає або видаляє акції. Для цього вам потрібно буде використовувати Web Sockets.
|
||||
**Історія користувача:** ви можете бачити зміни в режимі реального часу, коли будь-який інший користувач додає або видаляє акції. Для цього вам потрібно буде використовувати Web Sockets.
|
||||
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Then submit the URL to it in the Solution Link field. Optionally, also submit a link to your project's source code in the GitHub Link field.
|
||||
Після завершення переконайтеся, що демоверсія проєкту розміщена у відкритому доступі. Потім введіть URL-адресу проєкту в полі «Посилання на рішення». За бажанням введіть посилання на початковий код проєкту в полі «Посилання на GitHub».
|
||||
|
||||
# --solutions--
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7158d8c443eddfaeb5bd0f
|
||||
title: Керуйте клубом книжкової торгівлі
|
||||
title: Керуйте клубом книжкового обміну
|
||||
challengeType: 4
|
||||
forumTopicId: 302364
|
||||
dashedName: manage-a-book-trading-club
|
||||
@@ -8,19 +8,19 @@ dashedName: manage-a-book-trading-club
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://manage-a-book-trading-club.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://manage-a-book-trading-club.freecodecamp.rocks/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://manage-a-book-trading-club.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://manage-a-book-trading-club.freecodecamp.rocks/</a>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Я можу переглядати всі книги, опубліковані кожним користувачем.
|
||||
**Історія користувача:** я можу переглядати всі книжки, опубліковані іншими користувачами.
|
||||
|
||||
**Історія користувача:** Я можу додати нову книгу.
|
||||
**Історія користувача:** я можу додати нову книжку.
|
||||
|
||||
**Історія користувача:** Я можу оновити свої параметри, щоб зберегти своє повне ім'я, місто та країну.
|
||||
**Історія користувача:** я можу оновити свої параметри, щоб зберегти своє повне ім’я, місто та країну.
|
||||
|
||||
**Історія користувача:** Я можу запропонувати угоду та чекати, коли інший користувач прийме пропозицію.
|
||||
**Історія користувача:** я можу запропонувати обмін та чекати, коли інший користувач прийме пропозицію.
|
||||
|
||||
Як тільки ви закінчите реалізацію цих історій користувача, введіть URL-адресу вашого онлайн додатку і, за бажанням, вашого GitHub репозиторію. Тоді натисніть кнопку "Я завершив це завдання".
|
||||
Як тільки ви виконаєте історії користувачів, введіть URL-адресу вашого застосунку і, за бажанням, вашого репозиторію на GitHub. Потім натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
Ви можете отримати фідбек до свого проєкту, поділившись ним на <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">форумі freeCodeCamp</a>.
|
||||
|
||||
|
||||
@@ -8,17 +8,17 @@ dashedName: map-data-across-the-globe
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <https://codepen.io/freeCodeCamp/full/mVEJag>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <https://codepen.io/freeCodeCamp/full/mVEJag>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Я можу побачити на карті світу де приземлились всі метеорити.
|
||||
**Історія користувача:** я можу побачити на карті світу місця, де впали метеорити.
|
||||
|
||||
**Історія користувача:** Я можу сказати приблизний розмір метеорита, просто глянувши на те яким він зображений на карті.
|
||||
**Історія користувача:** я можу сказати приблизний розмір метеорита, просто глянувши на те, яким він зображений на карті.
|
||||
|
||||
**Історія користувача:** Я можу наводити курсор на точку знаходження метеорита для отримання додаткової інформації.
|
||||
**Історія користувача:** я можу навести курсор на точку знаходження метеорита для отримання додаткової інформації.
|
||||
|
||||
**Підказка:** Ось набір даних, які ви можете використовувати для побудови проєкту: <https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json>
|
||||
**Підказка:** ось набір даних, які ви можете використовувати для побудови проєкту: <https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json>
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -8,29 +8,29 @@ dashedName: p2p-video-chat-application
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://p2p-video-chat-application.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://p2p-video-chat-application.freecodecamp.rocks/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://p2p-video-chat-application.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://p2p-video-chat-application.freecodecamp.rocks/</a>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** При поверненні, браузер запропонує мені доступ до камери та мікрофона.
|
||||
**Історія користувача:** спершу браузер запропонує надати доступ до камери та мікрофона.
|
||||
|
||||
**Історія користувача:** Після того, як я надам дозвіл, мені потрібно ввести назву кімнати.
|
||||
**Історія користувача:** після того, як я надам дозвіл, мені потрібно ввести назву кімнати.
|
||||
|
||||
**Історія користувача:** Після введення ім'я, кімната буде створена, якщо раніше не існувало кімнати з тим же ім'ям.
|
||||
**Історія користувача:** після введення назви кімнати, вона буде створена, якщо раніше не існувало кімнати з тою ж назвою.
|
||||
|
||||
**Історія користувача:** Мій друг зможе згодом перейти на той самий вебсайт, ввести назву тієї самої кімнати, приєднатися до неї та тоді долучитися до відеочату зі мною.
|
||||
**Історія користувача:** мій друг зможе згодом перейти на той самий вебсайт, ввести назву тієї самої кімнати, приєднатися до неї та долучитися до відеочату зі мною.
|
||||
|
||||
**Історія користувача:** Якщо я введу ім'я кімнати, і у цій кімнаті уже є двоє людей, я отримую сповіщення про те, що кімната заповнена.
|
||||
**Історія користувача:** якщо я введу назву кімнати, і у цій кімнаті вже є двоє людей, я отримаю сповіщення про те, що кімната заповнена.
|
||||
|
||||
**Історія користувача:** Будь-хто може створити або приєднатися до будь-якої кімнати. І кількість кімнат необмежена, але всі вони повинні мати унікальні назви.
|
||||
**Історія користувача:** будь-хто може створити або приєднатися до будь-якої кімнати. Кількість кімнат необмежена, але вони повинні мати унікальні назви.
|
||||
|
||||
**Історія користувача:** Я можу заборонити сайту доступ до мого мікрофона та вебкамера. Якщо я забороню доступ або виникне якась проблема, я побачу сповіщення про те, що це необхідно.
|
||||
**Історія користувача:** я можу заборонити доступ до мого мікрофона та камери. Якщо я забороню доступ або виникне якась проблема, я побачу сповіщення про те, що це необхідно.
|
||||
|
||||
**Історія користувача:** Коли я виберу скасувати крок вводу даних кімнати або замість ім'я введу пропуски, мене знову попросять ввести коректне ім'я кімнати.
|
||||
**Історія користувача:** якщо я скасую крок вводу даних кімнати або замість назви введу пропуски, мене знову попросять ввести дійсну назву кімнати.
|
||||
|
||||
**Історія користувача:** Якщо одна із двох осіб у кімнаті від’єднається, вони можуть відновити зв'язок у тій самій кімнаті та продовжити спілкування.
|
||||
**Історія користувача:** якщо одна із двох осіб у кімнаті від’єднається, вони можуть відновити зв’язок у тій самій кімнаті та продовжити спілкування.
|
||||
|
||||
Як тільки ви виконаєте ці історії користувачів, введіть URL-адресу вашого онлайн додатку і, за можливості, вашого GitHub репозиторію. Тоді натисніть кнопку "Завдання виконано".
|
||||
Як тільки ви виконаєте історії користувачів, введіть URL-адресу вашого застосунку і, за бажанням, вашого репозиторію на GitHub. Потім натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
Ви можете отримати фідбек до свого проєкту, поділившись ним на <a href="https://forum.freecodecamp.org/c/project-feedback/409" target="_blank" rel="noopener noreferrer nofollow">форумі freeCodeCamp</a>.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7198d8c242eddfaeb5bd13
|
||||
title: Показати національну спільність за допомогою орієнтованого графу
|
||||
title: Зобразіть сусідні країни за допомогою силового алгоритму візуалізації графа
|
||||
challengeType: 3
|
||||
forumTopicId: 302367
|
||||
dashedName: show-national-contiguity-with-a-force-directed-graph
|
||||
@@ -8,17 +8,17 @@ dashedName: show-national-contiguity-with-a-force-directed-graph
|
||||
|
||||
# --description--
|
||||
|
||||
**Objective:** Build an app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/XWEONRz>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <https://codepen.io/freeCodeCamp/full/XWEONRz>.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** я бачу орієнтований граф, створений силовими алгоритмами, який показує, які країни мають спільні кордони.
|
||||
**Історія користувача:** я бачу силовий алгоритм візуалізації графів, який показує, які країни мають спільні кордони.
|
||||
|
||||
**Історія користувача:** Я можу бачити прапор кожної країни на її вузлі.
|
||||
**Історія користувача:** я можу побачити прапор кожної країни.
|
||||
|
||||
**Підказка:** Ось набір даних, які ви можете використовувати під час виконання проєкту: <https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json>
|
||||
**Підказка:** ось набір даних, які ви можете використовувати під час виконання проєкту: <https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json>
|
||||
|
||||
**Підказка:** Ви можете створити спрайт-аркуші національних прапорів тут: <https://www.flag-sprites.com>.
|
||||
**Підказка:** ви можете створити спрайтовий аркуш прапорів на <https://www.flag-sprites.com>.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7158d8c442eddfaeb5bd10
|
||||
title: Показати місцеву погоду
|
||||
title: Покажіть місцеву погоду
|
||||
challengeType: 3
|
||||
forumTopicId: 302368
|
||||
dashedName: show-the-local-weather
|
||||
@@ -8,19 +8,19 @@ dashedName: show-the-local-weather
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/bELRjV" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/bELRjV</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/bELRjV" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/bELRjV</a>.
|
||||
|
||||
**Правило #1:** Не дивіться на приклад коду проєкту. Визначте його самі.
|
||||
**Правило №1:** не дивіться на код проєкту в прикладі. Напишіть його власноруч.
|
||||
|
||||
**Правило №2:** виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**Історія користувача:** Я можу побачити погоду у своєму поточному місцеперебуванні.
|
||||
**Історія користувача:** я можу побачити погоду у своєму поточному місцеперебуванні.
|
||||
|
||||
**User Story:** Я можу бачити іншу піктограму або інше фонове зображення (наприклад, засніжена гора, спекотна пустеля) залежно від погоди.
|
||||
**Історія користувача:** я можу побачити іншу піктограму або інше фонове зображення (наприклад, засніжена гора, спекотна пустеля) залежно від погоди.
|
||||
|
||||
**Історія користувача:** Я можу натиснути кнопку для перемикання між Фаренгейтом та Цельсієм.
|
||||
**Історія користувача:** я можу натиснути кнопку для перемикання між Фаренгейтом та Цельсієм.
|
||||
|
||||
**Примітка:** Тепер багато інтернет-браузерів вимагають безпечне HTTP з'єднання (`https://`), щоб отримати місцеперебування користувача через геолокацію HTML5. For this reason, we recommend using HTML5 Geolocation to get user location and then use the freeCodeCamp Weather API <a href="https://weather-proxy.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://weather-proxy.freecodecamp.rocks/</a> which uses an HTTP Secure connection for the weather. Also, be sure to connect to <a href="https://codepen.io" target="_blank" rel="noopener noreferrer nofollow">CodePen.io</a> via `https://`.
|
||||
**Примітка:** багато інтернет-браузерів тепер вимагають безпечне з’єднання HTTP (`https://`), щоб отримати місцеперебування користувача через геолокацію HTML5. Через це ми рекомендуємо використовувати HTML5 Geolocation для того, щоб отримати локацію користувача, а потім використовувати API погоди freeCodeCamp <a href="https://weather-proxy.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://weather-proxy.freecodecamp.rocks/</a>, який використовує безпечне з’єднання HTTP для погоди. Також переконайтесь, що з’єднання з <a href="https://codepen.io" target="_blank" rel="noopener noreferrer nofollow">CodePen.io</a> відбувається через `https://`.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7158d8c442eddfaeb5bd1f
|
||||
title: Використання Twitch JSON API
|
||||
title: Використайте Twitch JSON API
|
||||
challengeType: 3
|
||||
forumTopicId: 19541
|
||||
dashedName: use-the-twitch-json-api
|
||||
@@ -8,21 +8,21 @@ dashedName: use-the-twitch-json-api
|
||||
|
||||
# --description--
|
||||
|
||||
**Мета:** Створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/Myvqmo/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/Myvqmo/</a>.
|
||||
**Мета:** створити застосунок, функціонально схожий до цього: <a href="https://codepen.io/freeCodeCamp/full/Myvqmo/" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/Myvqmo/</a>.
|
||||
|
||||
The Twitch API is a RESTful API that lets developers build creative integrations for the broader Twitch community.
|
||||
Twitch API — це RESTful API, який дозволяє розробникам створювати творчі інтеграції для ширшої спільноти Twitch.
|
||||
|
||||
Виконайте історію користувача та пройдіть тести. Використовуйте необхідні вам бібліотеки або API. Оформте за власним стилем.
|
||||
|
||||
**User Story:** I can see whether freeCodeCamp is currently streaming on Twitch.tv.
|
||||
**Історія користувача:** я можу побачити, чи freeCodeCamp проводить трансляцію на Twitch.tv.
|
||||
|
||||
**User Story:** I can click the status output and be sent directly to the freeCodeCamp's Twitch.tv channel.
|
||||
**Історія користувача:** я можу натиснути на статус користувача і перейти на канал freeCodeCamp на Twitch.tv.
|
||||
|
||||
**User Story:** If a Twitch user is currently streaming, I can see additional details about what they are streaming.
|
||||
**Історія користувача:** якщо користувач Twitch на цей момент проводить трансляцію, я можу подивитись додаткову інформацію про неї.
|
||||
|
||||
**Підказка:** Ось перелік імен користувачів, хто регулярно проводить трансляції: `["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]`
|
||||
**Підказка:** ось перелік користувачів, які регулярно проводять трансляції: `["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]`
|
||||
|
||||
**UPDATE:** Через зміни в умовах користування API Twitch.tv вимагає ключ доступу API, але ми створили спосіб його обійти. Use <a href="https://twitch-proxy.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://twitch-proxy.freecodecamp.rocks/</a> instead of Twitch's API base URL and you'll still be able to get account information, without needing to sign up for an API key.
|
||||
**ОНОВЛЕННЯ:** Twitch.tv вимагає ключ доступу API через зміни в умовах користування API, але ми знайшли інший спосіб. Використайте <a href="https://twitch-proxy.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://twitch-proxy.freecodecamp.rocks/</a> замість базового посилання на API Twitch, і ви зможете отримати інформацію облікового запису без реєстрації для отримання ключа API.
|
||||
|
||||
Коли закінчите, надайте посилання на свій проєкт на CodePen та натисніть кнопку «Я виконав(-ла) це завдання».
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ dashedName: step-31
|
||||
|
||||
CSS-властивість `clip` використовують для визначення видимих частин елемента. Встановіть селектору `span[class~="sr-only"]` властивість `clip` зі значенням `rect(1px, 1px, 1px, 1px)`.
|
||||
|
||||
Властивість `clip-path` визначає форму властивості `clip`. Set the `clip-path` property to the value of `inset(50%)`, forming the clip-path into a rectangle within the element.
|
||||
Властивість `clip-path` визначає форму властивості `clip`. Налаштуйте значення властивості `clip-path` на `inset(50%)`, створюючи всередині елемента прямокутник.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
@@ -35,49 +35,49 @@ const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?
|
||||
assert(text.includes('clip-path: inset(50%) !important;'));
|
||||
```
|
||||
|
||||
Your `span[class~="sr-only"]` selector should have the `height` property set to `1px !important`.
|
||||
Ваш селектор `span[class~="sr-only"]` повинен мати властивість `height` зі значенням `1px !important`.
|
||||
|
||||
```js
|
||||
const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?.cssText;
|
||||
assert(text.includes('height: 1px !important;'));
|
||||
```
|
||||
|
||||
Your `span[class~="sr-only"]` selector should have the `width` property set to `1px !important`.
|
||||
Ваш селектор `span[class~="sr-only"]` повинен мати властивість `width` зі значенням `1px !important`.
|
||||
|
||||
```js
|
||||
const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?.cssText;
|
||||
assert(text.includes('width: 1px !important;'));
|
||||
```
|
||||
|
||||
Your `span[class~="sr-only"]` selector should have the `position` property set to `absolute !important`.
|
||||
Ваш селектор `span[class~="sr-only"]` повинен мати властивість `position` зі значенням `absolute !important`.
|
||||
|
||||
```js
|
||||
const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?.cssText;
|
||||
assert(text.includes('position: absolute !important;'));
|
||||
```
|
||||
|
||||
Your `span[class~="sr-only"]` selector should have the `overflow` property set to `hidden !important`.
|
||||
Ваш селектор `span[class~="sr-only"]` повинен мати властивість `overflow` зі значенням `hidden !important`.
|
||||
|
||||
```js
|
||||
const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?.cssText;
|
||||
assert(text.includes('overflow: hidden !important;'));
|
||||
```
|
||||
|
||||
Your `span[class~="sr-only"]` selector should have the `white-space` property set to `nowrap !important`.
|
||||
Ваш селектор `span[class~="sr-only"]` повинен мати властивість `white-space` зі значенням `nowrap !important`.
|
||||
|
||||
```js
|
||||
const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?.cssText;
|
||||
assert(text.includes('white-space: nowrap !important;'));
|
||||
```
|
||||
|
||||
Your `span[class~="sr-only"]` selector should have the `padding` property set to `0 !important`.
|
||||
Ваш селектор `span[class~="sr-only"]` повинен мати властивість `padding` зі значенням `0 !important`.
|
||||
|
||||
```js
|
||||
const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?.cssText;
|
||||
assert(text.includes('padding: 0px !important;'));
|
||||
```
|
||||
|
||||
Your `span[class~="sr-only"]` selector should have the `margin` property set to `-1px !important`.
|
||||
Ваш селектор `span[class~="sr-only"]` повинен мати властивість `margin` зі значенням `-1px !important`.
|
||||
|
||||
```js
|
||||
const text = new __helpers.CSSHelp(document).getStyle('span[class~="sr-only"]')?.cssText;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
id: 63d8402e39c73468b059cd43
|
||||
title: "Data Graph Explorer"
|
||||
title: "Build a Data Graph Explorer"
|
||||
challengeType: 10
|
||||
dashedName: data-graph-explorer
|
||||
dashedName: build-a-data-graph-explorer
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You will be <a href="https://colab.research.google.com/github/freeCodeCamp/boilerplate-cat-and-dog-image-classifier/blob/master/fcc_cat_dog.ipynb" target="_blank" rel="noopener noreferrer nofollow">working on this project with Google Colaboratory</a>.
|
||||
You will be <a href="https://colab.research.google.com/#create=true" target="_blank" rel="noopener noreferrer nofollow">working on this project with Google Colaboratory</a>.
|
||||
|
||||
After going to that link, create a copy of the notebook either in your own account or locally. Once you complete the project and it passes the test (included at that link), submit your project link below. If you are submitting a Google Colaboratory link, make sure to turn on link sharing for "anyone with the link."
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
id: 63d8401e39c73468b059cd42
|
||||
title: "Financial Calculator"
|
||||
title: "Build a Financial Calculator"
|
||||
challengeType: 10
|
||||
dashedName: financial-calculator
|
||||
dashedName: build-a-financial-calculator
|
||||
---
|
||||
|
||||
# --description--
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
id: 63d83ffd39c73468b059cd40
|
||||
title: "Graphing Calculator"
|
||||
title: "Build a Graphing Calculator"
|
||||
challengeType: 10
|
||||
dashedName: graphing-calculator
|
||||
dashedName: build-a-graphing-calculator
|
||||
---
|
||||
|
||||
# --description--
|
||||
4
curriculum/challenges/ukrainian/17-college-algebra-with-python/build-a-multi-function-calculator/multi-function-calculator.md → curriculum/challenges/ukrainian/17-college-algebra-with-python/build-a-multi-function-calculator-project/build-a-multi-function-calculator.md
Normal file → Executable file
4
curriculum/challenges/ukrainian/17-college-algebra-with-python/build-a-multi-function-calculator/multi-function-calculator.md → curriculum/challenges/ukrainian/17-college-algebra-with-python/build-a-multi-function-calculator-project/build-a-multi-function-calculator.md
Normal file → Executable file
@@ -1,8 +1,8 @@
|
||||
---
|
||||
id: 63d83ff239c73468b059cd3f
|
||||
title: "Multi-Function Calculator"
|
||||
title: "Build a Multi-Function Calculator"
|
||||
challengeType: 10
|
||||
dashedName: multi-function-calculator
|
||||
dashedName: build-a-multi-function-calculator
|
||||
---
|
||||
|
||||
# --description--
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
id: 63d8401039c73468b059cd41
|
||||
title: "Three Math Games"
|
||||
title: "Build Three Math Games"
|
||||
challengeType: 10
|
||||
dashedName: three-math-games
|
||||
dashedName: build-three-math-games
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You will be <a href="https://colab.research.google.com/github/freeCodeCamp/boilerplate-cat-and-dog-image-classifier/blob/master/fcc_cat_dog.ipynb" target="_blank" rel="noopener noreferrer nofollow">working on this project with Google Colaboratory</a>.
|
||||
You will be <a href="https://colab.research.google.com/#create=true" target="_blank" rel="noopener noreferrer nofollow">working on this project with Google Colaboratory</a>.
|
||||
|
||||
After going to that link, create a copy of the notebook either in your own account or locally. Once you complete the project and it passes the test (included at that link), submit your project link below. If you are submitting a Google Colaboratory link, make sure to turn on link sharing for "anyone with the link."
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
id: 6363d2959078df117ce4c408
|
||||
title: "More Resources in Colab"
|
||||
challengeType: 15
|
||||
videoId: L5hh3Og9RCU
|
||||
videoId: HNFrRHqpck4
|
||||
dashedName: more-resources-in-colab
|
||||
---
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
id: 6363d2899078df117ce4c407
|
||||
title: "Spreadsheets and Additional Resources"
|
||||
challengeType: 15
|
||||
videoId: HNFrRHqpck4
|
||||
videoId: JH9Uk2mi3Dc
|
||||
dashedName: spreadsheets-and-additional-resources
|
||||
---
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ dashedName: exponents-and-logarithms
|
||||
|
||||
# --description--
|
||||
|
||||
Here is the <a href="https://colab.research.google.com/drive/1IVBaeX84arJXS73raRROaxbz4qMyFVb6?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook to go along with this video.</a>
|
||||
Here is the <a href="https://colab.research.google.com/drive/1hg7ecxGT20B8HR2mV75HzMylj9SHIWH8?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook to go along with this video.</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ dashedName: fractions-and-decimals-extra
|
||||
|
||||
The following video will show you one way to set up your Google Colaboratory notebook, so that you can continue to build your personalized algebra calculator.
|
||||
|
||||
Here is <a href="https://colab.research.google.com/drive/1ND_gULby6RWU4Zs27Z7V5WK2g7fHPk1b?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">the Colab notebook used in this video</a> so you can use it as a model.
|
||||
Here is <a href="https://colab.research.google.com/drive/1a_RtRtVfeO0m2528T4V-bCXozWf3HpM7?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">the Colab notebook used in this video</a> so you can use it as a model.
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ dashedName: graphing-systems
|
||||
|
||||
This first video will show you how to graph systems of equations with with written math, then code.
|
||||
|
||||
Here is the <a href="https://colab.research.google.com/drive/1tB7N3QqHEbGk33v0BdTwZTVkS9ju9yn6?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook used in this video.</a>
|
||||
Here is the <a href="https://colab.research.google.com/drive/1N1JEZJctODxsntROnmg0VqMSHXYdIlFD?usp=sharing" target="_blank" rel="noopener noreferrer nofollow">Colab notebook used in this video.</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Open the following Colab notebook, run the cell, and <a href="https://colab.rese
|
||||
|
||||
## --text--
|
||||
|
||||
If you import sympy and define x as a variable, what would be the input from the following code?
|
||||
If you import sympy and define x as a variable, what would be the output from the following code?
|
||||
|
||||
```py
|
||||
example = 3*x - 12
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: 5900f36e1000cf542c50fe80
|
||||
title: 'Problem 1: Multiples of 3 and 5'
|
||||
challengeType: 1
|
||||
forumTopicId: 301722
|
||||
dashedName: problem-1-multiples-of-3-and-5
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
|
||||
|
||||
Find the sum of all the multiples of 3 or 5 below the provided parameter value `number`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`multiplesOf3and5(10)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof multiplesOf3and5(10) === 'number');
|
||||
```
|
||||
|
||||
`multiplesOf3and5(49)` should return 543.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(49), 543);
|
||||
```
|
||||
|
||||
`multiplesOf3and5(1000)` should return 233168.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(1000), 233168);
|
||||
```
|
||||
|
||||
`multiplesOf3and5(8456)` should return 16687353.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(8456), 16687353);
|
||||
```
|
||||
|
||||
`multiplesOf3and5(19564)` should return 89301183.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(19564), 89301183);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function multiplesOf3and5(number) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
multiplesOf3and5(1000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const multiplesOf3and5 = (number) => {
|
||||
var total = 0;
|
||||
|
||||
for(var i = 0; i < number; i++) {
|
||||
if(i % 3 == 0 || i % 5 == 0) {
|
||||
total += i;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
id: 5900f3761000cf542c50fe89
|
||||
title: 'Problem 10: Summation of primes'
|
||||
challengeType: 1
|
||||
forumTopicId: 301723
|
||||
dashedName: problem-10-summation-of-primes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
|
||||
|
||||
Find the sum of all the primes below `n`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`primeSummation(17)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof primeSummation(17) === 'number');
|
||||
```
|
||||
|
||||
`primeSummation(17)` should return 41.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(17), 41);
|
||||
```
|
||||
|
||||
`primeSummation(2001)` should return 277050.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(2001), 277050);
|
||||
```
|
||||
|
||||
`primeSummation(140759)` should return 873608362.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(140759), 873608362);
|
||||
```
|
||||
|
||||
`primeSummation(2000000)` should return 142913828922.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(2000000), 142913828922);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function primeSummation(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
primeSummation(2000000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
class PrimeSeive {
|
||||
constructor(num) {
|
||||
const seive = Array(Math.floor((num - 1) / 2)).fill(true);
|
||||
const upper = Math.floor((num - 1) / 2);
|
||||
const sqrtUpper = Math.floor((Math.sqrt(num) - 1) / 2);
|
||||
|
||||
for (let i = 0; i <= sqrtUpper; i++) {
|
||||
if (seive[i]) {
|
||||
// Mark value in seive array
|
||||
const prime = 2 * i + 3;
|
||||
// Mark all multiples of this number as false (not prime)
|
||||
const primeSqaredIndex = 2 * i ** 2 + 6 * i + 3;
|
||||
for (let j = primeSqaredIndex; j < upper; j += prime) {
|
||||
seive[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._seive = seive;
|
||||
}
|
||||
|
||||
isPrime(num) {
|
||||
return num === 2
|
||||
? true
|
||||
: num % 2 === 0
|
||||
? false
|
||||
: this.isOddPrime(num);
|
||||
}
|
||||
|
||||
isOddPrime(num) {
|
||||
return this._seive[(num - 3) / 2];
|
||||
}
|
||||
};
|
||||
|
||||
function primeSummation(num) {
|
||||
const primeSeive = new PrimeSeive(num);
|
||||
|
||||
let sum = 2;
|
||||
for (let i = 3; i < num; i += 2) {
|
||||
if (primeSeive.isOddPrime(i)) sum += i;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 5900f3d01000cf542c50fee3
|
||||
title: 'Problem 100: Arranged probability'
|
||||
challengeType: 1
|
||||
forumTopicId: 301724
|
||||
dashedName: problem-100-arranged-probability
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If a box contains twenty-one colored discs, composed of fifteen blue discs and six red discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs.
|
||||
|
||||
$${P(BB)} = \frac{15}{21}×\frac{14}{20} = \frac{1}{2}$$
|
||||
|
||||
The next such arrangement, for which there is exactly a 50% chance of taking two blue discs at random, is a box containing eighty-five blue discs and thirty-five red discs.
|
||||
|
||||
By finding the first arrangement to contain over `limit` discs in total, determine the number of blue discs that the box would contain.
|
||||
|
||||
# --hints--
|
||||
|
||||
`arrangedProbability(20)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof arrangedProbability(10) === 'number');
|
||||
```
|
||||
|
||||
`arrangedProbability(20)` should return `15`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(arrangedProbability(20), 15);
|
||||
```
|
||||
|
||||
`arrangedProbability(100)` should return `85`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(arrangedProbability(100), 85);
|
||||
```
|
||||
|
||||
`arrangedProbability(100000)` should return `97513`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(arrangedProbability(100000), 97513);
|
||||
```
|
||||
|
||||
`arrangedProbability(1000000000)` should return `3822685023`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(arrangedProbability(1000000000), 3822685023);
|
||||
```
|
||||
|
||||
`arrangedProbability(1000000000000)` should return `756872327473`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(arrangedProbability(1000000000000), 756872327473);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function arrangedProbability(limit) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
arrangedProbability(20);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function arrangedProbability(limit) {
|
||||
// Based on https://www.mathblog.dk/project-euler-100-blue-discs-two-blue/
|
||||
let blue = 15;
|
||||
let discs = 21;
|
||||
|
||||
while (discs < limit) {
|
||||
const nextBlue = 3 * blue + 2 * discs - 2;
|
||||
const nextDiscs = 4 * blue + 3 * discs - 3;
|
||||
|
||||
blue = nextBlue;
|
||||
discs = nextDiscs;
|
||||
}
|
||||
return blue;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,182 @@
|
||||
---
|
||||
id: 5900f3781000cf542c50fe8a
|
||||
title: 'Problem 11: Largest product in a grid'
|
||||
challengeType: 1
|
||||
forumTopicId: 301734
|
||||
dashedName: problem-11-largest-product-in-a-grid
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
|
||||
|
||||
<div style='text-align: center;'>
|
||||
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08<br>
|
||||
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00<br>
|
||||
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65<br>
|
||||
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91<br>
|
||||
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80<br>
|
||||
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50<br>
|
||||
32 98 81 28 64 23 67 10 <span style='color: red'><b>26</b></span> 38 40 67 59 54 70 66 18 38 64 70<br>
|
||||
67 26 20 68 02 62 12 20 95 <span style='color: red'><b>63</b></span> 94 39 63 08 40 91 66 49 94 21<br>
|
||||
24 55 58 05 66 73 99 26 97 17 <span style='color: red'><b>78</b></span> 78 96 83 14 88 34 89 63 72<br>
|
||||
21 36 23 09 75 00 76 44 20 45 35 <span style='color: red'><b>14</b></span> 00 61 33 97 34 31 33 95<br>
|
||||
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92<br>
|
||||
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57<br>
|
||||
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58<br>
|
||||
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40<br>
|
||||
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66<br>
|
||||
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69<br>
|
||||
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36<br>
|
||||
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16<br>
|
||||
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54<br>
|
||||
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48<br>
|
||||
</div>
|
||||
|
||||
The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
|
||||
|
||||
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in a given `arr` grid?
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestGridProduct(testGrid)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof largestGridProduct(testGrid) === 'number');
|
||||
```
|
||||
|
||||
`largestGridProduct(testGrid)` should return 14169081.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestGridProduct(testGrid), 14169081);
|
||||
```
|
||||
|
||||
`largestGridProduct(grid)` should return 70600674.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestGridProduct(grid), 70600674);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function largestGridProduct(arr) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
const grid = [
|
||||
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
|
||||
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
|
||||
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
|
||||
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
|
||||
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
|
||||
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
|
||||
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
|
||||
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
|
||||
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
|
||||
[21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
|
||||
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
|
||||
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
|
||||
[86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
|
||||
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
|
||||
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
|
||||
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
|
||||
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
|
||||
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
|
||||
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
|
||||
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
|
||||
];
|
||||
|
||||
const testGrid = [
|
||||
[40, 17, 81, 18, 57],
|
||||
[74, 4, 36, 16, 29],
|
||||
[36, 42, 69, 73, 45],
|
||||
[51, 54, 69, 16, 92],
|
||||
[7, 97, 57, 32, 16]
|
||||
];
|
||||
|
||||
largestGridProduct(testGrid);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function largestGridProduct(arr) {
|
||||
let maxProduct = 0;
|
||||
let currProduct = 0;
|
||||
|
||||
function maxProductChecker(n) {
|
||||
if (n > maxProduct) {
|
||||
return maxProduct = n;
|
||||
}
|
||||
}
|
||||
|
||||
// loop rows
|
||||
for (let r = 0; r < arr.length; r++) {
|
||||
// loop columns
|
||||
for (let c = 0; c < arr[r].length; c++) {
|
||||
const limit = arr[r].length - 3;
|
||||
|
||||
// check horizontal
|
||||
if (c < limit) {
|
||||
currProduct = arr[r][c] * arr[r][c + 1] * arr[r][c + 2] * arr[r][c + 3];
|
||||
maxProductChecker(currProduct);
|
||||
}
|
||||
|
||||
// check vertical
|
||||
if (r < limit) {
|
||||
currProduct = arr[r][c] * arr[r + 1][c] * arr[r + 2][c] * arr[r + 3][c];
|
||||
maxProductChecker(currProduct);
|
||||
}
|
||||
|
||||
// check diagonal [\]
|
||||
if (c < limit && r < limit) {
|
||||
currProduct = arr[r][c] * arr[r + 1][c + 1] * arr[r + 2][c + 2] * arr[r + 3][c + 3];
|
||||
maxProductChecker(currProduct);
|
||||
}
|
||||
|
||||
// check diagonal [/]
|
||||
if (c > 3 && r < limit) {
|
||||
currProduct = arr[r][c] * arr[r + 1][c - 1] * arr[r + 2][c - 2] * arr[r + 3][c - 3];
|
||||
maxProductChecker(currProduct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return maxProduct;
|
||||
}
|
||||
|
||||
const grid = [ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
|
||||
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
|
||||
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
|
||||
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
|
||||
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
|
||||
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
|
||||
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
|
||||
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
|
||||
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
|
||||
[21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
|
||||
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
|
||||
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
|
||||
[86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
|
||||
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
|
||||
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
|
||||
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
|
||||
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
|
||||
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
|
||||
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
|
||||
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
|
||||
];
|
||||
|
||||
const testGrid = [
|
||||
[40, 17, 81, 18, 57],
|
||||
[74, 4, 36, 16, 29],
|
||||
[36, 42, 69, 73, 45],
|
||||
[51, 54, 69, 16, 92],
|
||||
[7, 97, 57, 32, 16]
|
||||
];
|
||||
```
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
id: 5900f3781000cf542c50fe8b
|
||||
title: 'Problem 12: Highly divisible triangular number'
|
||||
challengeType: 1
|
||||
forumTopicId: 301746
|
||||
dashedName: problem-12-highly-divisible-triangular-number
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
|
||||
|
||||
<div style='text-align: center;'>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...</div>
|
||||
|
||||
Let us list the factors of the first seven triangle numbers:
|
||||
|
||||
<div style='padding-left: 4em;'><b>1:</b> 1</div>
|
||||
<div style='padding-left: 4em;'><b>3:</b> 1, 3</div>
|
||||
<div style='padding-left: 4em;'><b>6:</b> 1, 2, 3, 6</div>
|
||||
<div style='padding-left: 4em;'><b>10:</b> 1, 2, 5, 10</div>
|
||||
<div style='padding-left: 4em;'><b>15:</b> 1, 3, 5, 15</div>
|
||||
<div style='padding-left: 4em;'><b>21:</b> 1, 3, 7, 21</div>
|
||||
<div style='padding-left: 4em;'><b>28:</b> 1, 2, 4, 7, 14, 28</div>
|
||||
|
||||
We can see that 28 is the first triangle number to have over five divisors.
|
||||
|
||||
What is the value of the first triangle number to have over `n` divisors?
|
||||
|
||||
# --hints--
|
||||
|
||||
`divisibleTriangleNumber(5)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof divisibleTriangleNumber(5) === 'number');
|
||||
```
|
||||
|
||||
`divisibleTriangleNumber(5)` should return 28.
|
||||
|
||||
```js
|
||||
assert.strictEqual(divisibleTriangleNumber(5), 28);
|
||||
```
|
||||
|
||||
`divisibleTriangleNumber(23)` should return 630.
|
||||
|
||||
```js
|
||||
assert.strictEqual(divisibleTriangleNumber(23), 630);
|
||||
```
|
||||
|
||||
`divisibleTriangleNumber(167)` should return 1385280.
|
||||
|
||||
```js
|
||||
assert.strictEqual(divisibleTriangleNumber(167), 1385280);
|
||||
```
|
||||
|
||||
`divisibleTriangleNumber(374)` should return 17907120.
|
||||
|
||||
```js
|
||||
assert.strictEqual(divisibleTriangleNumber(374), 17907120);
|
||||
```
|
||||
|
||||
`divisibleTriangleNumber(500)` should return 76576500.
|
||||
|
||||
```js
|
||||
assert.strictEqual(divisibleTriangleNumber(500), 76576500);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function divisibleTriangleNumber(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
divisibleTriangleNumber(500);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function divisibleTriangleNumber(n) {
|
||||
if (n === 1) return 3;
|
||||
let counter = 1;
|
||||
let triangleNumber = counter++;
|
||||
|
||||
|
||||
while (noOfFactors(triangleNumber) < n) {
|
||||
triangleNumber += counter++;
|
||||
}
|
||||
return triangleNumber;
|
||||
}
|
||||
|
||||
function noOfFactors(num) {
|
||||
const primeFactors = getPrimeFactors(num);
|
||||
let prod = 1;
|
||||
for(let p in primeFactors) {
|
||||
prod *= (primeFactors[p] + 1)
|
||||
}
|
||||
return prod;
|
||||
}
|
||||
|
||||
function getPrimeFactors(num) {
|
||||
let n = num;
|
||||
let primes = {};
|
||||
|
||||
let p = 2;
|
||||
let sqrt = Math.sqrt(num);
|
||||
|
||||
function checkAndUpdate(inc) {
|
||||
if (n % p === 0) {
|
||||
const curr = primes[p];
|
||||
if (curr) {
|
||||
primes[p]++
|
||||
} else {
|
||||
primes[p] = 1;
|
||||
}
|
||||
n /= p;
|
||||
} else {
|
||||
p += inc;
|
||||
}
|
||||
}
|
||||
|
||||
while(p === 2 && p <= n) {
|
||||
checkAndUpdate(1);
|
||||
}
|
||||
|
||||
while (p <= n && p <= sqrt) {
|
||||
checkAndUpdate(2);
|
||||
}
|
||||
if(Object.keys(primes).length === 0) {
|
||||
primes[num] = 1;
|
||||
} else if(n !== 1) {
|
||||
primes[n] = 1;
|
||||
}
|
||||
return primes;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,286 @@
|
||||
---
|
||||
id: 5900f37a1000cf542c50fe8c
|
||||
title: 'Problem 13: Large sum'
|
||||
challengeType: 1
|
||||
forumTopicId: 301757
|
||||
dashedName: problem-13-large-sum
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
37107287533902102798797998220837590246510135740250<br>
|
||||
46376937677490009712648124896970078050417018260538<br>
|
||||
74324986199524741059474233309513058123726617309629<br>
|
||||
91942213363574161572522430563301811072406154908250<br>
|
||||
23067588207539346171171980310421047513778063246676<br>
|
||||
89261670696623633820136378418383684178734361726757<br>
|
||||
28112879812849979408065481931592621691275889832738<br>
|
||||
44274228917432520321923589422876796487670272189318<br>
|
||||
47451445736001306439091167216856844588711603153276<br>
|
||||
70386486105843025439939619828917593665686757934951<br>
|
||||
62176457141856560629502157223196586755079324193331<br>
|
||||
64906352462741904929101432445813822663347944758178<br>
|
||||
92575867718337217661963751590579239728245598838407<br>
|
||||
58203565325359399008402633568948830189458628227828<br>
|
||||
80181199384826282014278194139940567587151170094390<br>
|
||||
35398664372827112653829987240784473053190104293586<br>
|
||||
86515506006295864861532075273371959191420517255829<br>
|
||||
71693888707715466499115593487603532921714970056938<br>
|
||||
54370070576826684624621495650076471787294438377604<br>
|
||||
53282654108756828443191190634694037855217779295145<br>
|
||||
36123272525000296071075082563815656710885258350721<br>
|
||||
45876576172410976447339110607218265236877223636045<br>
|
||||
17423706905851860660448207621209813287860733969412<br>
|
||||
81142660418086830619328460811191061556940512689692<br>
|
||||
51934325451728388641918047049293215058642563049483<br>
|
||||
62467221648435076201727918039944693004732956340691<br>
|
||||
15732444386908125794514089057706229429197107928209<br>
|
||||
55037687525678773091862540744969844508330393682126<br>
|
||||
18336384825330154686196124348767681297534375946515<br>
|
||||
80386287592878490201521685554828717201219257766954<br>
|
||||
78182833757993103614740356856449095527097864797581<br>
|
||||
16726320100436897842553539920931837441497806860984<br>
|
||||
48403098129077791799088218795327364475675590848030<br>
|
||||
87086987551392711854517078544161852424320693150332<br>
|
||||
59959406895756536782107074926966537676326235447210<br>
|
||||
69793950679652694742597709739166693763042633987085<br>
|
||||
41052684708299085211399427365734116182760315001271<br>
|
||||
65378607361501080857009149939512557028198746004375<br>
|
||||
35829035317434717326932123578154982629742552737307<br>
|
||||
94953759765105305946966067683156574377167401875275<br>
|
||||
88902802571733229619176668713819931811048770190271<br>
|
||||
25267680276078003013678680992525463401061632866526<br>
|
||||
36270218540497705585629946580636237993140746255962<br>
|
||||
24074486908231174977792365466257246923322810917141<br>
|
||||
91430288197103288597806669760892938638285025333403<br>
|
||||
34413065578016127815921815005561868836468420090470<br>
|
||||
23053081172816430487623791969842487255036638784583<br>
|
||||
11487696932154902810424020138335124462181441773470<br>
|
||||
63783299490636259666498587618221225225512486764533<br>
|
||||
67720186971698544312419572409913959008952310058822<br>
|
||||
95548255300263520781532296796249481641953868218774<br>
|
||||
76085327132285723110424803456124867697064507995236<br>
|
||||
37774242535411291684276865538926205024910326572967<br>
|
||||
23701913275725675285653248258265463092207058596522<br>
|
||||
29798860272258331913126375147341994889534765745501<br>
|
||||
18495701454879288984856827726077713721403798879715<br>
|
||||
38298203783031473527721580348144513491373226651381<br>
|
||||
34829543829199918180278916522431027392251122869539<br>
|
||||
40957953066405232632538044100059654939159879593635<br>
|
||||
29746152185502371307642255121183693803580388584903<br>
|
||||
41698116222072977186158236678424689157993532961922<br>
|
||||
62467957194401269043877107275048102390895523597457<br>
|
||||
23189706772547915061505504953922979530901129967519<br>
|
||||
86188088225875314529584099251203829009407770775672<br>
|
||||
11306739708304724483816533873502340845647058077308<br>
|
||||
82959174767140363198008187129011875491310547126581<br>
|
||||
97623331044818386269515456334926366572897563400500<br>
|
||||
42846280183517070527831839425882145521227251250327<br>
|
||||
55121603546981200581762165212827652751691296897789<br>
|
||||
32238195734329339946437501907836945765883352399886<br>
|
||||
75506164965184775180738168837861091527357929701337<br>
|
||||
62177842752192623401942399639168044983993173312731<br>
|
||||
32924185707147349566916674687634660915035914677504<br>
|
||||
99518671430235219628894890102423325116913619626622<br>
|
||||
73267460800591547471830798392868535206946944540724<br>
|
||||
76841822524674417161514036427982273348055556214818<br>
|
||||
97142617910342598647204516893989422179826088076852<br>
|
||||
87783646182799346313767754307809363333018982642090<br>
|
||||
10848802521674670883215120185883543223812876952786<br>
|
||||
71329612474782464538636993009049310363619763878039<br>
|
||||
62184073572399794223406235393808339651327408011116<br>
|
||||
66627891981488087797941876876144230030984490851411<br>
|
||||
60661826293682836764744779239180335110989069790714<br>
|
||||
85786944089552990653640447425576083659976645795096<br>
|
||||
66024396409905389607120198219976047599490197230297<br>
|
||||
64913982680032973156037120041377903785566085089252<br>
|
||||
16730939319872750275468906903707539413042652315011<br>
|
||||
94809377245048795150954100921645863754710598436791<br>
|
||||
78639167021187492431995700641917969777599028300699<br>
|
||||
15368713711936614952811305876380278410754449733078<br>
|
||||
40789923115535562561142322423255033685442488917353<br>
|
||||
44889911501440648020369068063960672322193204149535<br>
|
||||
41503128880339536053299340368006977710650566631954<br>
|
||||
81234880673210146739058568557934581403627822703280<br>
|
||||
82616570773948327592232845941706525094512325230608<br>
|
||||
22918802058777319719839450180888072429661980811197<br>
|
||||
77158542502016545090413245809786882778948721859617<br>
|
||||
72107838435069186155435662884062257473692284509516<br>
|
||||
20849603980134001723930671666823555245252804609722<br>
|
||||
53503534226472524250874054075591789781264330331690<br>
|
||||
</div>
|
||||
|
||||
# --hints--
|
||||
|
||||
`largeSum(testNums)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof largeSum(testNums) === 'number');
|
||||
```
|
||||
|
||||
`largeSum(testNums)` should return 8348422521.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largeSum(testNums), 8348422521);
|
||||
```
|
||||
|
||||
`largeSum(fiftyDigitNums)` should return 5537376230.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largeSum(fiftyDigitNums), 5537376230);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
const fiftyDigitNums = [
|
||||
'37107287533902102798797998220837590246510135740250',
|
||||
'46376937677490009712648124896970078050417018260538',
|
||||
'74324986199524741059474233309513058123726617309629',
|
||||
'91942213363574161572522430563301811072406154908250',
|
||||
'23067588207539346171171980310421047513778063246676',
|
||||
'89261670696623633820136378418383684178734361726757',
|
||||
'28112879812849979408065481931592621691275889832738',
|
||||
'44274228917432520321923589422876796487670272189318',
|
||||
'47451445736001306439091167216856844588711603153276',
|
||||
'70386486105843025439939619828917593665686757934951',
|
||||
'62176457141856560629502157223196586755079324193331',
|
||||
'64906352462741904929101432445813822663347944758178',
|
||||
'92575867718337217661963751590579239728245598838407',
|
||||
'58203565325359399008402633568948830189458628227828',
|
||||
'80181199384826282014278194139940567587151170094390',
|
||||
'35398664372827112653829987240784473053190104293586',
|
||||
'86515506006295864861532075273371959191420517255829',
|
||||
'71693888707715466499115593487603532921714970056938',
|
||||
'54370070576826684624621495650076471787294438377604',
|
||||
'53282654108756828443191190634694037855217779295145',
|
||||
'36123272525000296071075082563815656710885258350721',
|
||||
'45876576172410976447339110607218265236877223636045',
|
||||
'17423706905851860660448207621209813287860733969412',
|
||||
'81142660418086830619328460811191061556940512689692',
|
||||
'51934325451728388641918047049293215058642563049483',
|
||||
'62467221648435076201727918039944693004732956340691',
|
||||
'15732444386908125794514089057706229429197107928209',
|
||||
'55037687525678773091862540744969844508330393682126',
|
||||
'18336384825330154686196124348767681297534375946515',
|
||||
'80386287592878490201521685554828717201219257766954',
|
||||
'78182833757993103614740356856449095527097864797581',
|
||||
'16726320100436897842553539920931837441497806860984',
|
||||
'48403098129077791799088218795327364475675590848030',
|
||||
'87086987551392711854517078544161852424320693150332',
|
||||
'59959406895756536782107074926966537676326235447210',
|
||||
'69793950679652694742597709739166693763042633987085',
|
||||
'41052684708299085211399427365734116182760315001271',
|
||||
'65378607361501080857009149939512557028198746004375',
|
||||
'35829035317434717326932123578154982629742552737307',
|
||||
'94953759765105305946966067683156574377167401875275',
|
||||
'88902802571733229619176668713819931811048770190271',
|
||||
'25267680276078003013678680992525463401061632866526',
|
||||
'36270218540497705585629946580636237993140746255962',
|
||||
'24074486908231174977792365466257246923322810917141',
|
||||
'91430288197103288597806669760892938638285025333403',
|
||||
'34413065578016127815921815005561868836468420090470',
|
||||
'23053081172816430487623791969842487255036638784583',
|
||||
'11487696932154902810424020138335124462181441773470',
|
||||
'63783299490636259666498587618221225225512486764533',
|
||||
'67720186971698544312419572409913959008952310058822',
|
||||
'95548255300263520781532296796249481641953868218774',
|
||||
'76085327132285723110424803456124867697064507995236',
|
||||
'37774242535411291684276865538926205024910326572967',
|
||||
'23701913275725675285653248258265463092207058596522',
|
||||
'29798860272258331913126375147341994889534765745501',
|
||||
'18495701454879288984856827726077713721403798879715',
|
||||
'38298203783031473527721580348144513491373226651381',
|
||||
'34829543829199918180278916522431027392251122869539',
|
||||
'40957953066405232632538044100059654939159879593635',
|
||||
'29746152185502371307642255121183693803580388584903',
|
||||
'41698116222072977186158236678424689157993532961922',
|
||||
'62467957194401269043877107275048102390895523597457',
|
||||
'23189706772547915061505504953922979530901129967519',
|
||||
'86188088225875314529584099251203829009407770775672',
|
||||
'11306739708304724483816533873502340845647058077308',
|
||||
'82959174767140363198008187129011875491310547126581',
|
||||
'97623331044818386269515456334926366572897563400500',
|
||||
'42846280183517070527831839425882145521227251250327',
|
||||
'55121603546981200581762165212827652751691296897789',
|
||||
'32238195734329339946437501907836945765883352399886',
|
||||
'75506164965184775180738168837861091527357929701337',
|
||||
'62177842752192623401942399639168044983993173312731',
|
||||
'32924185707147349566916674687634660915035914677504',
|
||||
'99518671430235219628894890102423325116913619626622',
|
||||
'73267460800591547471830798392868535206946944540724',
|
||||
'76841822524674417161514036427982273348055556214818',
|
||||
'97142617910342598647204516893989422179826088076852',
|
||||
'87783646182799346313767754307809363333018982642090',
|
||||
'10848802521674670883215120185883543223812876952786',
|
||||
'71329612474782464538636993009049310363619763878039',
|
||||
'62184073572399794223406235393808339651327408011116',
|
||||
'66627891981488087797941876876144230030984490851411',
|
||||
'60661826293682836764744779239180335110989069790714',
|
||||
'85786944089552990653640447425576083659976645795096',
|
||||
'66024396409905389607120198219976047599490197230297',
|
||||
'64913982680032973156037120041377903785566085089252',
|
||||
'16730939319872750275468906903707539413042652315011',
|
||||
'94809377245048795150954100921645863754710598436791',
|
||||
'78639167021187492431995700641917969777599028300699',
|
||||
'15368713711936614952811305876380278410754449733078',
|
||||
'40789923115535562561142322423255033685442488917353',
|
||||
'44889911501440648020369068063960672322193204149535',
|
||||
'41503128880339536053299340368006977710650566631954',
|
||||
'81234880673210146739058568557934581403627822703280',
|
||||
'82616570773948327592232845941706525094512325230608',
|
||||
'22918802058777319719839450180888072429661980811197',
|
||||
'77158542502016545090413245809786882778948721859617',
|
||||
'72107838435069186155435662884062257473692284509516',
|
||||
'20849603980134001723930671666823555245252804609722',
|
||||
'53503534226472524250874054075591789781264330331690'
|
||||
];
|
||||
|
||||
const testNums = [
|
||||
'37107287533902102798797998220837590246510135740250',
|
||||
'46376937677490009712648124896970078050417018260538'
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function largeSum(arr) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
const testNums = [
|
||||
'37107287533902102798797998220837590246510135740250',
|
||||
'46376937677490009712648124896970078050417018260538'
|
||||
];
|
||||
|
||||
largeSum(testNums);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function largeSum(arr) {
|
||||
|
||||
let sum = 0;
|
||||
|
||||
arr.forEach(function(num) {
|
||||
sum += parseInt(num, 10);
|
||||
});
|
||||
|
||||
sum = sum.toString(10);
|
||||
|
||||
sum = sum.substring(0, 1) + sum.substring(2);
|
||||
|
||||
let firstTen = sum.slice(0, 10);
|
||||
return parseInt(firstTen, 10);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,111 @@
|
||||
---
|
||||
id: 5900f37a1000cf542c50fe8d
|
||||
title: 'Problem 14: Longest Collatz sequence'
|
||||
challengeType: 1
|
||||
forumTopicId: 301768
|
||||
dashedName: problem-14-longest-collatz-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The following iterative sequence is defined for the set of positive integers:
|
||||
|
||||
<div style='padding-left: 4em;'><var>n</var> → <var>n</var>/2 (<var>n</var> is even)</div>
|
||||
|
||||
<div style='padding-left: 4em;'><var>n</var> → 3<var>n</var> + 1 (<var>n</var> is odd)</div>
|
||||
|
||||
Using the rule above and starting with 13, we generate the following sequence:
|
||||
|
||||
<div style='text-align: center;'>13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1</div>
|
||||
|
||||
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
|
||||
|
||||
Which starting number, under the given `limit`, produces the longest chain?
|
||||
|
||||
**Note:** Once the chain starts the terms are allowed to go above `limit`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`longestCollatzSequence(14)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof longestCollatzSequence(14) === 'number');
|
||||
```
|
||||
|
||||
`longestCollatzSequence(14)` should return 9.
|
||||
|
||||
```js
|
||||
assert.strictEqual(longestCollatzSequence(14), 9);
|
||||
```
|
||||
|
||||
`longestCollatzSequence(5847)` should return 3711.
|
||||
|
||||
```js
|
||||
assert.strictEqual(longestCollatzSequence(5847), 3711);
|
||||
```
|
||||
|
||||
`longestCollatzSequence(46500)` should return 35655.
|
||||
|
||||
```js
|
||||
assert.strictEqual(longestCollatzSequence(46500), 35655);
|
||||
```
|
||||
|
||||
`longestCollatzSequence(54512)` should return 52527.
|
||||
|
||||
```js
|
||||
assert.strictEqual(longestCollatzSequence(54512), 52527);
|
||||
```
|
||||
|
||||
`longestCollatzSequence(100000)` should return 77031.
|
||||
|
||||
```js
|
||||
assert.strictEqual(longestCollatzSequence(100000), 77031);
|
||||
```
|
||||
|
||||
`longestCollatzSequence(1000000)` should return 837799.
|
||||
|
||||
```js
|
||||
assert.strictEqual(longestCollatzSequence(1000000), 837799);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function longestCollatzSequence(limit) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
longestCollatzSequence(14);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function longestCollatzSequence(limit) {
|
||||
let longest = 1;
|
||||
let maxLength = 1;
|
||||
for (let i = Math.floor(limit / 2); i < limit; i++) {
|
||||
let len = colLen(i);
|
||||
if (len > maxLength) {
|
||||
longest = i;
|
||||
maxLength = len;
|
||||
}
|
||||
}
|
||||
return longest;
|
||||
}
|
||||
|
||||
const knownSequence = { '1': 1 };
|
||||
|
||||
function colLen(n) {
|
||||
if (knownSequence[n]) {
|
||||
return knownSequence[n];
|
||||
} else {
|
||||
const len = n % 2 === 0 ? colLen(n / 2) + 1 : colLen((3 * n + 1) / 2) + 2;
|
||||
knownSequence[n] = len;
|
||||
return len;
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 5900f37b1000cf542c50fe8e
|
||||
title: 'Problem 15: Lattice paths'
|
||||
challengeType: 1
|
||||
forumTopicId: 301780
|
||||
dashedName: problem-15-lattice-paths
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
|
||||
|
||||
<img class="img-responsive center-block" alt="a diagram of 6 2 by 2 grids showing all the routes to the bottom right corner" src="https://cdn-media-1.freecodecamp.org/project-euler/1Atixoj.gif" style="background-color: white; padding: 10px;" />
|
||||
|
||||
How many such routes are there through a given `gridSize`?
|
||||
|
||||
# --hints--
|
||||
|
||||
`latticePaths(4)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof latticePaths(4) === 'number');
|
||||
```
|
||||
|
||||
`latticePaths(4)` should return 70.
|
||||
|
||||
```js
|
||||
assert.strictEqual(latticePaths(4), 70);
|
||||
```
|
||||
|
||||
`latticePaths(9)` should return 48620.
|
||||
|
||||
```js
|
||||
assert.strictEqual(latticePaths(9), 48620);
|
||||
```
|
||||
|
||||
`latticePaths(20)` should return 137846528820.
|
||||
|
||||
```js
|
||||
assert.strictEqual(latticePaths(20), 137846528820);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function latticePaths(gridSize) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
latticePaths(4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function latticePaths(gridSize) {
|
||||
let paths = 1;
|
||||
|
||||
for (let i = 0; i < gridSize; i++) {
|
||||
paths *= (2 * gridSize) - i;
|
||||
paths /= i + 1;
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
id: 5900f37d1000cf542c50fe8f
|
||||
title: 'Problem 16: Power digit sum'
|
||||
challengeType: 1
|
||||
forumTopicId: 301791
|
||||
dashedName: problem-16-power-digit-sum
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
2<sup>15</sup> = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
|
||||
|
||||
What is the sum of the digits of the number 2<sup><code>exponent</code></sup>?
|
||||
|
||||
# --hints--
|
||||
|
||||
`powerDigitSum(15)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof powerDigitSum(15) === 'number');
|
||||
```
|
||||
|
||||
`powerDigitSum(15)` should return 26.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerDigitSum(15), 26);
|
||||
```
|
||||
|
||||
`powerDigitSum(128)` should return 166.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerDigitSum(128), 166);
|
||||
```
|
||||
|
||||
`powerDigitSum(1000)` should return 1366.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerDigitSum(1000), 1366);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function powerDigitSum(exponent) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
powerDigitSum(15);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function powerDigitSum(exponent) {
|
||||
const bigNum = [1];
|
||||
let sum = 0;
|
||||
|
||||
for (let i = 1; i <= exponent; i++) {
|
||||
let count = bigNum.length + 1;
|
||||
let overflow = 0;
|
||||
for (let j = 0; j < count; j++) {
|
||||
let digit = bigNum[j] || 0;
|
||||
digit = 2 * digit + overflow;
|
||||
|
||||
if (digit > 9) {
|
||||
digit -= 10;
|
||||
overflow = 1;
|
||||
} else {
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
bigNum[j] = digit;
|
||||
}
|
||||
}
|
||||
|
||||
bigNum.forEach(function(num) {
|
||||
return sum += num;
|
||||
});
|
||||
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,130 @@
|
||||
---
|
||||
id: 5900f37d1000cf542c50fe90
|
||||
title: 'Problem 17: Number letter counts'
|
||||
challengeType: 1
|
||||
forumTopicId: 301804
|
||||
dashedName: problem-17-number-letter-counts
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
|
||||
|
||||
If all the numbers from 1 to given `limit` inclusive were written out in words, how many letters would be used?
|
||||
|
||||
**Note:** Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
|
||||
|
||||
# --hints--
|
||||
|
||||
`numberLetterCounts(5)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof numberLetterCounts(5) === 'number');
|
||||
```
|
||||
|
||||
`numberLetterCounts(5)` should return 19.
|
||||
|
||||
```js
|
||||
assert.strictEqual(numberLetterCounts(5), 19);
|
||||
```
|
||||
|
||||
`numberLetterCounts(150)` should return 1903.
|
||||
|
||||
```js
|
||||
assert.strictEqual(numberLetterCounts(150), 1903);
|
||||
```
|
||||
|
||||
`numberLetterCounts(1000)` should return 21124.
|
||||
|
||||
```js
|
||||
assert.strictEqual(numberLetterCounts(1000), 21124);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function numberLetterCounts(limit) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
numberLetterCounts(5);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function numberLetterCounts(limit) {
|
||||
const dictionary = {
|
||||
0: '',
|
||||
1: 'one',
|
||||
2: 'two',
|
||||
3: 'three',
|
||||
4: 'four',
|
||||
5: 'five',
|
||||
6: 'six',
|
||||
7: 'seven',
|
||||
8: 'eight',
|
||||
9: 'nine',
|
||||
10: 'ten',
|
||||
11: 'eleven',
|
||||
12: 'twelve',
|
||||
13: 'thirteen',
|
||||
14: 'fourteen',
|
||||
15: 'fifteen',
|
||||
16: 'sixteen',
|
||||
17: 'seventeen',
|
||||
18: 'eighteen',
|
||||
19: 'nineteen',
|
||||
20: 'twenty',
|
||||
30: 'thirty',
|
||||
40: 'forty',
|
||||
50: 'fifty',
|
||||
60: 'sixty',
|
||||
70: 'seventy',
|
||||
80: 'eighty',
|
||||
90: 'ninety',
|
||||
1000: 'onethousand'
|
||||
};
|
||||
|
||||
let numString = '';
|
||||
|
||||
function convertToString(num) {
|
||||
// check dictionary for number
|
||||
if (dictionary[num]) {
|
||||
return dictionary[num];
|
||||
} else {
|
||||
const hundreds = Math.floor(num / 100);
|
||||
const tens = Math.floor((num / 10) % 10) * 10;
|
||||
const remainder = num % 10;
|
||||
|
||||
let tempStr = '';
|
||||
|
||||
if (hundreds === 0) {
|
||||
tempStr += dictionary[tens] + dictionary[remainder];
|
||||
} else {
|
||||
tempStr += dictionary[hundreds] + 'hundred';
|
||||
|
||||
if (tens !== 0 || remainder !== 0) {
|
||||
tempStr += 'and';
|
||||
}
|
||||
|
||||
if (tens < 20) {
|
||||
const lessThanTwenty = tens + remainder;
|
||||
tempStr += dictionary[lessThanTwenty];
|
||||
} else {
|
||||
tempStr += dictionary[tens] + dictionary[remainder];
|
||||
}
|
||||
}
|
||||
return tempStr;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 1; i <= limit; i++) {
|
||||
numString += convertToString(i);
|
||||
}
|
||||
return numString.length;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
id: 5900f37e1000cf542c50fe91
|
||||
title: 'Problem 18: Maximum path sum I'
|
||||
challengeType: 1
|
||||
forumTopicId: 301815
|
||||
dashedName: problem-18-maximum-path-sum-i
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
|
||||
|
||||
<span style='display: block; text-align: center;'>
|
||||
<strong style='color: red;'>3</strong><br>
|
||||
<strong style='color: red;'>7</strong> 4<br>
|
||||
2 <strong style='color: red;'>4</strong> 6<br>
|
||||
8 5 <strong style='color: red;'>9</strong> 3
|
||||
</span>
|
||||
|
||||
That is, 3 + 7 + 4 + 9 = 23.
|
||||
|
||||
Find the maximum total from top to bottom of the triangle below:
|
||||
|
||||
75
|
||||
95 64
|
||||
17 47 82
|
||||
18 35 87 10
|
||||
20 04 82 47 65
|
||||
19 01 23 75 03 34
|
||||
88 02 77 73 07 63 67
|
||||
99 65 04 28 06 16 70 92
|
||||
41 41 26 56 83 40 80 70 33
|
||||
41 48 72 33 47 32 37 16 94 29
|
||||
53 71 44 65 25 43 91 52 97 51 14
|
||||
70 11 33 28 77 73 17 78 39 68 17 57
|
||||
91 71 52 38 17 14 91 43 58 50 27 29 48
|
||||
63 66 04 68 89 53 67 30 73 16 69 87 40 31
|
||||
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
|
||||
|
||||
**NOTE:** As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
|
||||
|
||||
# --hints--
|
||||
|
||||
`maximumPathSumI(testTriangle)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof maximumPathSumI(testTriangle) === 'number');
|
||||
```
|
||||
|
||||
`maximumPathSumI(testTriangle)` should return 23.
|
||||
|
||||
```js
|
||||
assert.strictEqual(maximumPathSumI(testTriangle), 23);
|
||||
```
|
||||
|
||||
`maximumPathSumI(numTriangle)` should return 1074.
|
||||
|
||||
```js
|
||||
assert.strictEqual(maximumPathSumI(numTriangle), 1074);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
const numTriangle = [[75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [95, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [17, 47, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [18, 35, 87, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [20, 4, 82, 47, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [19, 1, 23, 75, 3, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0], [88, 2, 77, 73, 7, 63, 67, 0, 0, 0, 0, 0, 0, 0, 0], [99, 65, 4, 28, 6, 16, 70, 92, 0, 0, 0, 0, 0, 0, 0], [41, 41, 26, 56, 83, 40, 80, 70, 33, 0, 0, 0, 0, 0, 0], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29, 0, 0, 0, 0, 0], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14, 0, 0, 0, 0], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57, 0, 0, 0], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48, 0, 0], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31, 0], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function maximumPathSumI(triangle) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
const testTriangle = [[3, 0, 0, 0],
|
||||
[7, 4, 0, 0],
|
||||
[2, 4, 6, 0],
|
||||
[8, 5, 9, 3]];
|
||||
|
||||
maximumPathSumI(testTriangle);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const testTriangle = [[3, 0, 0, 0],
|
||||
[7, 4, 0, 0],
|
||||
[2, 4, 6, 0],
|
||||
[8, 5, 9, 3]];
|
||||
|
||||
function maximumPathSumI(triangle) {
|
||||
let maxSum = triangle.slice();
|
||||
|
||||
for (let i = triangle.length - 1; i > 0; i--) {
|
||||
let currentRow = maxSum[i];
|
||||
let previousRow = maxSum[i - 1];
|
||||
const temp = [];
|
||||
for (let j = 0; j < i; j++) {
|
||||
temp.push(Math.max((currentRow[j] + previousRow[j]), (currentRow[j + 1] + previousRow[j])));
|
||||
}
|
||||
maxSum[i - 1] = temp;
|
||||
maxSum.pop();
|
||||
}
|
||||
return maxSum[0][0];
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 5900f37f1000cf542c50fe92
|
||||
title: 'Problem 19: Counting Sundays'
|
||||
challengeType: 1
|
||||
forumTopicId: 301827
|
||||
dashedName: problem-19-counting-sundays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You are given the following information, but you may prefer to do some research for yourself.
|
||||
|
||||
<ul>
|
||||
<li>1 Jan 1900 was a Monday.</li>
|
||||
<li>Thirty days has September,<br>April, June and November.<br>All the rest have thirty-one,<br>Saving February alone,<br>Which has twenty-eight, rain or shine.<br>And on leap years, twenty-nine.</li>
|
||||
<li>A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.</li>
|
||||
</ul>
|
||||
|
||||
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
|
||||
|
||||
# --hints--
|
||||
|
||||
`countingSundays(1943, 1946)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof countingSundays(1943, 1946) === 'number');
|
||||
```
|
||||
|
||||
`countingSundays(1943, 1946)` should return 6.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countingSundays(1943, 1946), 6);
|
||||
```
|
||||
|
||||
`countingSundays(1995, 2000)` should return 10.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countingSundays(1995, 2000), 10);
|
||||
```
|
||||
|
||||
`countingSundays(1901, 2000)` should return 171.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countingSundays(1901, 2000), 171);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countingSundays(firstYear, lastYear) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
countingSundays(1943, 1946);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countingSundays(firstYear, lastYear) {
|
||||
let sundays = 0;
|
||||
|
||||
for (let year = firstYear; year <= lastYear; year++) {
|
||||
for (let month = 0; month <= 11; month++) {
|
||||
const thisDate = new Date(year, month, 1);
|
||||
if (thisDate.getDay() === 0) {
|
||||
sundays++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sundays;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,103 @@
|
||||
---
|
||||
id: 5900f36e1000cf542c50fe81
|
||||
title: 'Problem 2: Even Fibonacci Numbers'
|
||||
challengeType: 1
|
||||
forumTopicId: 301838
|
||||
dashedName: problem-2-even-fibonacci-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
|
||||
|
||||
<div style='text-align: center;'>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</div>
|
||||
|
||||
By considering the terms in the Fibonacci sequence whose values do not exceed `n`, find the sum of the even-valued terms.
|
||||
|
||||
# --hints--
|
||||
|
||||
`fiboEvenSum(10)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof fiboEvenSum(10) === 'number');
|
||||
```
|
||||
|
||||
Your function should return an even value.
|
||||
|
||||
```js
|
||||
assert.equal(fiboEvenSum(10) % 2 === 0, true);
|
||||
```
|
||||
|
||||
Your function should sum the even-valued Fibonacci numbers: `fiboEvenSum(8)` should return 10.
|
||||
|
||||
```js
|
||||
assert.strictEqual(fiboEvenSum(8), 10);
|
||||
```
|
||||
|
||||
`fiboEvenSum(10)` should return 10.
|
||||
|
||||
```js
|
||||
assert.strictEqual(fiboEvenSum(10), 10);
|
||||
```
|
||||
|
||||
`fiboEvenSum(34)` should return 44.
|
||||
|
||||
```js
|
||||
assert.strictEqual(fiboEvenSum(34), 44);
|
||||
```
|
||||
|
||||
`fiboEvenSum(60)` should return 44.
|
||||
|
||||
```js
|
||||
assert.strictEqual(fiboEvenSum(60), 44);
|
||||
```
|
||||
|
||||
`fiboEvenSum(1000)` should return 798.
|
||||
|
||||
```js
|
||||
assert.strictEqual(fiboEvenSum(1000), 798);
|
||||
```
|
||||
|
||||
`fiboEvenSum(100000)` should return 60696.
|
||||
|
||||
```js
|
||||
assert.strictEqual(fiboEvenSum(100000), 60696);
|
||||
```
|
||||
|
||||
`fiboEvenSum(4000000)` should return 4613732.
|
||||
|
||||
```js
|
||||
assert.strictEqual(fiboEvenSum(4000000), 4613732);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fiboEvenSum(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const fiboEvenSum = (number) => {
|
||||
if (number <= 1) {
|
||||
return 0;
|
||||
} else {
|
||||
let evenSum = 0,
|
||||
prevFibNum = 1,
|
||||
fibNum = 2; // According to problem description our Fibonacci series starts with 1, 2
|
||||
for (let i = 2; fibNum <= number; i++) {
|
||||
if (fibNum % 2 == 0) {
|
||||
evenSum += fibNum;
|
||||
}
|
||||
[prevFibNum, fibNum] = [fibNum, prevFibNum + fibNum];
|
||||
}
|
||||
return evenSum;
|
||||
}
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 5900f3801000cf542c50fe93
|
||||
title: 'Problem 20: Factorial digit sum'
|
||||
challengeType: 1
|
||||
forumTopicId: 301839
|
||||
dashedName: problem-20-factorial-digit-sum
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`n`! means `n` × (`n` − 1) × ... × 3 × 2 × 1
|
||||
|
||||
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
|
||||
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
|
||||
|
||||
Find the sum of the digits `n`!
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumFactorialDigits(10)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof sumFactorialDigits(10) === 'number');
|
||||
```
|
||||
|
||||
`sumFactorialDigits(10)` should return 27.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumFactorialDigits(10), 27);
|
||||
```
|
||||
|
||||
`sumFactorialDigits(25)` should return 72.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumFactorialDigits(25), 72);
|
||||
```
|
||||
|
||||
`sumFactorialDigits(50)` should return 216.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumFactorialDigits(50), 216);
|
||||
```
|
||||
|
||||
`sumFactorialDigits(75)` should return 432.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumFactorialDigits(75), 432);
|
||||
```
|
||||
|
||||
`sumFactorialDigits(100)` should return 648.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumFactorialDigits(100), 648);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sumFactorialDigits(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
sumFactorialDigits(100);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let factorial = (n) => n <= 1 ? BigInt(n) : BigInt(n) * BigInt(factorial(--n));
|
||||
|
||||
let sumDigits = n => n.toString().split('').map(x => parseInt(x)).reduce((a,b) => a + b);
|
||||
|
||||
function sumFactorialDigits(n) {
|
||||
return sumDigits(factorial(n));
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 5900f3811000cf542c50fe94
|
||||
title: 'Problem 21: Amicable numbers'
|
||||
challengeType: 1
|
||||
forumTopicId: 301851
|
||||
dashedName: problem-21-amicable-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let d(`n`) be defined as the sum of proper divisors of `n` (numbers less than `n` which divide evenly into `n`).
|
||||
|
||||
If d(`a`) = `b` and d(`b`) = `a`, where `a` ≠ `b`, then `a` and `b` are an amicable pair and each of `a` and `b` are called amicable numbers.
|
||||
|
||||
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
|
||||
|
||||
Evaluate the sum of all the amicable numbers under `n`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumAmicableNum(1000)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof sumAmicableNum(1000) === 'number');
|
||||
```
|
||||
|
||||
`sumAmicableNum(1000)` should return 504.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumAmicableNum(1000), 504);
|
||||
```
|
||||
|
||||
`sumAmicableNum(2000)` should return 2898.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumAmicableNum(2000), 2898);
|
||||
```
|
||||
|
||||
`sumAmicableNum(5000)` should return 8442.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumAmicableNum(5000), 8442);
|
||||
```
|
||||
|
||||
`sumAmicableNum(10000)` should return 31626.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sumAmicableNum(10000), 31626);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sumAmicableNum(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
sumAmicableNum(10000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const sumAmicableNum = (n) => {
|
||||
const fsum = (n) => {
|
||||
let sum = 1;
|
||||
for (let i = 2; i <= Math.floor(Math.sqrt(n)); i++)
|
||||
if (Math.floor(n % i) === 0)
|
||||
sum += i + Math.floor(n / i);
|
||||
return sum;
|
||||
};
|
||||
let d = [];
|
||||
let amicableSum = 0;
|
||||
for (let i=2; i<n; i++) d[i] = fsum(i);
|
||||
for (let i=2; i<n; i++) {
|
||||
let dsum = d[i];
|
||||
if (d[dsum]===i && i!==dsum) amicableSum += i+dsum;
|
||||
}
|
||||
return amicableSum/2;
|
||||
};
|
||||
```
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 5900f3831000cf542c50fe96
|
||||
title: 'Problem 23: Non-abundant sums'
|
||||
challengeType: 1
|
||||
forumTopicId: 301873
|
||||
dashedName: problem-23-non-abundant-sums
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
|
||||
|
||||
A number `n` is called deficient if the sum of its proper divisors is less than `n` and it is called abundant if this sum exceeds `n`.
|
||||
|
||||
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
|
||||
|
||||
Find the sum of all positive integers <= `n` which cannot be written as the sum of two abundant numbers.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumOfNonAbundantNumbers(10000)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof sumOfNonAbundantNumbers(10000) === 'number');
|
||||
```
|
||||
|
||||
`sumOfNonAbundantNumbers(10000)` should return 3731004.
|
||||
|
||||
```js
|
||||
assert(sumOfNonAbundantNumbers(10000) === 3731004);
|
||||
```
|
||||
|
||||
`sumOfNonAbundantNumbers(15000)` should return 4039939.
|
||||
|
||||
```js
|
||||
assert(sumOfNonAbundantNumbers(15000) === 4039939);
|
||||
```
|
||||
|
||||
`sumOfNonAbundantNumbers(20000)` should return 4159710.
|
||||
|
||||
```js
|
||||
assert(sumOfNonAbundantNumbers(20000) === 4159710);
|
||||
```
|
||||
|
||||
`sumOfNonAbundantNumbers(28123)` should return 4179871.
|
||||
|
||||
```js
|
||||
assert(sumOfNonAbundantNumbers(28123) === 4179871);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sumOfNonAbundantNumbers(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
sumOfNonAbundantNumbers(28123);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function abundantCheck(number) {
|
||||
let sum = 1;
|
||||
|
||||
for (let i = 2; i <= Math.sqrt(number); i += 1) {
|
||||
if(number % i === 0) {
|
||||
sum += i + +(i !== Math.sqrt(number) && number / i);
|
||||
}
|
||||
}
|
||||
return sum > number;
|
||||
}
|
||||
|
||||
function sumOfNonAbundantNumbers(n) {
|
||||
let sum = 0;
|
||||
const memo = {};
|
||||
let abundantList = [];
|
||||
|
||||
// Function checkSum checks if num can be represented as a sum of numbers in the stack (array)
|
||||
const checkSum = (num, stack, memo) => {
|
||||
for (let i = 0; i < stack.length; i += 1) {
|
||||
if ((num - stack[i]) in memo) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
for (let i = 1; i <= n; i += 1) {
|
||||
if (abundantCheck(i)) {
|
||||
abundantList.push(i);
|
||||
memo[i] = 1;
|
||||
}
|
||||
if (checkSum(i, abundantList, memo)) continue;
|
||||
sum += i;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 5900f3841000cf542c50fe97
|
||||
title: 'Problem 24: Lexicographic permutations'
|
||||
challengeType: 1
|
||||
forumTopicId: 301885
|
||||
dashedName: problem-24-lexicographic-permutations
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
|
||||
|
||||
<div style='text-align: center;'>012 021 102 120 201 210</div>
|
||||
|
||||
What is the `n`th lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
|
||||
|
||||
# --hints--
|
||||
|
||||
`lexicographicPermutations(699999)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof lexicographicPermutations(699999) === 'number');
|
||||
```
|
||||
|
||||
`lexicographicPermutations(699999)` should return 1938246570.
|
||||
|
||||
```js
|
||||
assert(lexicographicPermutations(699999) == 1938246570);
|
||||
```
|
||||
|
||||
`lexicographicPermutations(899999)` should return 2536987410.
|
||||
|
||||
```js
|
||||
assert(lexicographicPermutations(899999) == 2536987410);
|
||||
```
|
||||
|
||||
`lexicographicPermutations(900000)` should return 2537014689.
|
||||
|
||||
```js
|
||||
assert(lexicographicPermutations(900000) == 2537014689);
|
||||
```
|
||||
|
||||
`lexicographicPermutations(999999)` should return 2783915460.
|
||||
|
||||
```js
|
||||
assert(lexicographicPermutations(999999) == 2783915460);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function lexicographicPermutations(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
lexicographicPermutations(999999);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
id: 5900f3851000cf542c50fe98
|
||||
title: 'Problem 25: 1000-digit Fibonacci number'
|
||||
challengeType: 1
|
||||
forumTopicId: 301897
|
||||
dashedName: problem-25-1000-digit-fibonacci-number
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The Fibonacci sequence is defined by the recurrence relation:
|
||||
|
||||
<div style='padding-left: 4em;'>F<sub>n</sub> = F<sub>n−1</sub> + F<sub>n−2</sub>, where F<sub>1</sub> = 1 and F<sub>2</sub> = 1.</div>
|
||||
|
||||
Hence the first 12 terms will be:
|
||||
|
||||
<div style='padding-left: 4em; display: inline-grid; grid-template-rows: auto; row-gap: 7px;'><div>F<sub>1</sub> = 1</div><div>F<sub>2</sub> = 1</div><div>F<sub>3</sub> = 2</div><div>F<sub>4</sub> = 3</div><div>F<sub>5</sub> = 5</div><div>F<sub>6</sub> = 8</div><div>F<sub>7</sub> = 13</div><div>F<sub>8</sub> = 21</div><div>F<sub>9</sub> = 34</div><div>F<sub>10</sub> = 55</div><div>F<sub>11</sub> = 89</div><div>F<sub>12</sub> = 144</div></div>
|
||||
|
||||
The 12th term, F<sub>12</sub>, is the first term to contain three digits.
|
||||
|
||||
What is the index of the first term in the Fibonacci sequence to contain `n` digits?
|
||||
|
||||
# --hints--
|
||||
|
||||
`digitFibonacci(5)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof digitFibonacci(5) === 'number');
|
||||
```
|
||||
|
||||
`digitFibonacci(5)` should return 21.
|
||||
|
||||
```js
|
||||
assert.strictEqual(digitFibonacci(5), 21);
|
||||
```
|
||||
|
||||
`digitFibonacci(10)` should return 45.
|
||||
|
||||
```js
|
||||
assert.strictEqual(digitFibonacci(10), 45);
|
||||
```
|
||||
|
||||
`digitFibonacci(15)` should return 69.
|
||||
|
||||
```js
|
||||
assert.strictEqual(digitFibonacci(15), 69);
|
||||
```
|
||||
|
||||
`digitFibonacci(20)` should return 93.
|
||||
|
||||
```js
|
||||
assert.strictEqual(digitFibonacci(20), 93);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function digitFibonacci(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
digitFibonacci(20);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const digitFibonacci = (n) => {
|
||||
const digits = (num) => {
|
||||
return num.toString().length;
|
||||
};
|
||||
let f1 = 1;
|
||||
let f2 = 1;
|
||||
let index = 3;
|
||||
while (true) {
|
||||
let fn = f1 + f2;
|
||||
if (digits(fn) === n) return index;
|
||||
[f1, f2] = [f2, fn];
|
||||
index++;
|
||||
}
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 5900f3861000cf542c50fe99
|
||||
title: 'Problem 26: Reciprocal cycles'
|
||||
challengeType: 1
|
||||
forumTopicId: 301908
|
||||
dashedName: problem-26-reciprocal-cycles
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
|
||||
|
||||
<div style='padding-left: 4em; display: inline-grid; grid-template-rows: auto; row-gap: 7px;'><div><sup>1</sup>/<sub>2</sub> = 0.5</div><div><sup>1</sup>/<sub>3</sub> = 0.(3)</div><div><sup>1</sup>/<sub>4</sub> = 0.25</div><div><sup>1</sup>/<sub>5</sub> = 0.2</div><div><sup>1</sup>/<sub>6</sub> = 0.1(6)</div><div><sup>1</sup>/<sub>7</sub> = 0.(142857)</div><div><sup>1</sup>/<sub>8</sub> = 0.125</div><div><sup>1</sup>/<sub>9</sub> = 0.(1)</div><div><sup>1</sup>/<sub>10</sub> = 0.1</div></div>
|
||||
|
||||
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that <sup>1</sup>/<sub>7</sub> has a 6-digit recurring cycle.
|
||||
|
||||
Find the value of `d` < `n` for which <sup>1</sup>/<sub>d</sub> contains the longest recurring cycle in its decimal fraction part.
|
||||
|
||||
# --hints--
|
||||
|
||||
`reciprocalCycles(700)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof reciprocalCycles(700) === 'number');
|
||||
```
|
||||
|
||||
`reciprocalCycles(700)` should return 659.
|
||||
|
||||
```js
|
||||
assert(reciprocalCycles(700) == 659);
|
||||
```
|
||||
|
||||
`reciprocalCycles(800)` should return 743.
|
||||
|
||||
```js
|
||||
assert(reciprocalCycles(800) == 743);
|
||||
```
|
||||
|
||||
`reciprocalCycles(900)` should return 887.
|
||||
|
||||
```js
|
||||
assert(reciprocalCycles(900) == 887);
|
||||
```
|
||||
|
||||
`reciprocalCycles(1000)` should return 983.
|
||||
|
||||
```js
|
||||
assert(reciprocalCycles(1000) == 983);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function reciprocalCycles(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
reciprocalCycles(1000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 5900f3871000cf542c50fe9a
|
||||
title: 'Problem 27: Quadratic primes'
|
||||
challengeType: 1
|
||||
forumTopicId: 301919
|
||||
dashedName: problem-27-quadratic-primes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Euler discovered the remarkable quadratic formula:
|
||||
|
||||
<div style='margin-left: 4em;'>$n^2 + n + 41$</div>
|
||||
|
||||
It turns out that the formula will produce 40 primes for the consecutive integer values $0 \\le n \\le 39$. However, when $n = 40, 40^2 + 40 + 41 = 40(40 + 1) + 41$ is divisible by 41, and certainly when $n = 41, 41^2 + 41 + 41$ is clearly divisible by 41.
|
||||
|
||||
The incredible formula $n^2 - 79n + 1601$ was discovered, which produces 80 primes for the consecutive values $0 \\le n \\le 79$. The product of the coefficients, −79 and 1601, is −126479.
|
||||
|
||||
Considering quadratics of the form:
|
||||
|
||||
<div style='margin-left: 4em;'>
|
||||
$n^2 + an + b$, where $|a| < range$ and $|b| \le range$<br>
|
||||
where $|n|$ is the modulus/absolute value of $n$<br>
|
||||
e.g. $|11| = 11$ and $|-4| = 4$<br>
|
||||
</div>
|
||||
|
||||
Find the product of the coefficients, $a$ and $b$, for the quadratic expression that produces the maximum number of primes for consecutive values of $n$, starting with $n = 0$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`quadraticPrimes(200)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof quadraticPrimes(200) === 'number');
|
||||
```
|
||||
|
||||
`quadraticPrimes(200)` should return -4925.
|
||||
|
||||
```js
|
||||
assert(quadraticPrimes(200) == -4925);
|
||||
```
|
||||
|
||||
`quadraticPrimes(500)` should return -18901.
|
||||
|
||||
```js
|
||||
assert(quadraticPrimes(500) == -18901);
|
||||
```
|
||||
|
||||
`quadraticPrimes(800)` should return -43835.
|
||||
|
||||
```js
|
||||
assert(quadraticPrimes(800) == -43835);
|
||||
```
|
||||
|
||||
`quadraticPrimes(1000)` should return -59231.
|
||||
|
||||
```js
|
||||
assert(quadraticPrimes(1000) == -59231);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function quadraticPrimes(range) {
|
||||
|
||||
return range;
|
||||
}
|
||||
|
||||
quadraticPrimes(1000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 5900f3881000cf542c50fe9b
|
||||
title: 'Problem 28: Number spiral diagonals'
|
||||
challengeType: 1
|
||||
forumTopicId: 301930
|
||||
dashedName: problem-28-number-spiral-diagonals
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
<div style='color: red; display: inline;'>21</div> 22 23 24 <div style='color: red; display: inline;'>25</div><br>
|
||||
20 <div style='color: red; display: inline;'>7</div> 8 <div style='color: red; display: inline;'>9</div> 10<br>
|
||||
19 6 <div style='color: red; display: inline;'>1</div> 2 11<br>
|
||||
18 <div style='color: red; display: inline;'>5</div> 4 <div style='color: red; display: inline;'>3</div> 12<br>
|
||||
<div style='color: red; display: inline;'>17</div> 16 15 14 <div style='color: red; display: inline;'>13</div><br>
|
||||
</div>
|
||||
|
||||
It can be verified that the sum of the numbers on the diagonals is 101.
|
||||
|
||||
What is the sum of the numbers on the diagonals in an `n` by `n` spiral formed in the same way?
|
||||
|
||||
# --hints--
|
||||
|
||||
`spiralDiagonals(101)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof spiralDiagonals(101) === 'number');
|
||||
```
|
||||
|
||||
`spiralDiagonals(101)` should return 692101.
|
||||
|
||||
```js
|
||||
assert(spiralDiagonals(101) == 692101);
|
||||
```
|
||||
|
||||
`spiralDiagonals(303)` should return 18591725.
|
||||
|
||||
```js
|
||||
assert(spiralDiagonals(303) == 18591725);
|
||||
```
|
||||
|
||||
`spiralDiagonals(505)` should return 85986601.
|
||||
|
||||
```js
|
||||
assert(spiralDiagonals(505) == 85986601);
|
||||
```
|
||||
|
||||
`spiralDiagonals(1001)` should return 669171001.
|
||||
|
||||
```js
|
||||
assert(spiralDiagonals(1001) == 669171001);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function spiralDiagonals(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
spiralDiagonals(1001);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const spiralDiagonals = (n) => {
|
||||
const Sn2 = (n) => {
|
||||
return n*(n+1)*(2*n+1)/6;
|
||||
};
|
||||
const Sn = (n) => {
|
||||
return n*(n+1)/2;
|
||||
};
|
||||
let sum = (Sn2(n-1) + Sn(n-1) + n-1) + (Math.floor(n/2) + Sn2(n));
|
||||
return sum;
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 5900f3891000cf542c50fe9c
|
||||
title: 'Problem 29: Distinct powers'
|
||||
challengeType: 1
|
||||
forumTopicId: 301941
|
||||
dashedName: problem-29-distinct-powers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Consider all integer combinations of $a^b$ for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
2<sup>2</sup>=4, 2<sup>3</sup>=8, 2<sup>4</sup>=16, 2<sup>5</sup>=32 <br>
|
||||
3<sup>2</sup>=9, 3<sup>3</sup>=27, 3<sup>4</sup>=81, 3<sup>5</sup>=243 <br>
|
||||
4<sup>2</sup>=16, 4<sup>3</sup>=64, 4<sup>4</sup>=256, 4<sup>5</sup>=1024 <br>
|
||||
5<sup>2</sup>=25, 5<sup>3</sup>=125, 5<sup>4</sup>=625, 5<sup>5</sup>=3125 <br>
|
||||
</div>
|
||||
|
||||
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
|
||||
</div>
|
||||
|
||||
How many distinct terms are in the sequence generated by $a^b$ for 2 ≤ `a` ≤ `n` and 2 ≤ `b` ≤ `n`?
|
||||
|
||||
# --hints--
|
||||
|
||||
`distinctPowers(15)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof distinctPowers(15) === 'number');
|
||||
```
|
||||
|
||||
`distinctPowers(15)` should return 177.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPowers(15), 177);
|
||||
```
|
||||
|
||||
`distinctPowers(20)` should return 324.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPowers(20), 324);
|
||||
```
|
||||
|
||||
`distinctPowers(25)` should return 519.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPowers(25), 519);
|
||||
```
|
||||
|
||||
`distinctPowers(30)` should return 755.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPowers(30), 755);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function distinctPowers(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
distinctPowers(30);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const distinctPowers = (n) => {
|
||||
let list = [];
|
||||
for (let a=2; a<=n; a++) {
|
||||
for (let b=2; b<=n; b++) {
|
||||
let term = Math.pow(a, b);
|
||||
if (list.indexOf(term)===-1) list.push(term);
|
||||
}
|
||||
}
|
||||
return list.length;
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 5900f36f1000cf542c50fe82
|
||||
title: 'Problem 3: Largest prime factor'
|
||||
challengeType: 1
|
||||
forumTopicId: 301952
|
||||
dashedName: problem-3-largest-prime-factor
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The prime factors of 13195 are 5, 7, 13 and 29.
|
||||
|
||||
What is the largest prime factor of the given `number`?
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestPrimeFactor(2)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof largestPrimeFactor(2) === 'number');
|
||||
```
|
||||
|
||||
`largestPrimeFactor(2)` should return 2.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPrimeFactor(2), 2);
|
||||
```
|
||||
|
||||
`largestPrimeFactor(3)` should return 3.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPrimeFactor(3), 3);
|
||||
```
|
||||
|
||||
`largestPrimeFactor(5)` should return 5.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPrimeFactor(5), 5);
|
||||
```
|
||||
|
||||
`largestPrimeFactor(7)` should return 7.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPrimeFactor(7), 7);
|
||||
```
|
||||
|
||||
`largestPrimeFactor(8)` should return 2.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPrimeFactor(8), 2);
|
||||
```
|
||||
|
||||
`largestPrimeFactor(13195)` should return 29.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPrimeFactor(13195), 29);
|
||||
```
|
||||
|
||||
`largestPrimeFactor(600851475143)` should return 6857.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPrimeFactor(600851475143), 6857);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function largestPrimeFactor(number) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
largestPrimeFactor(13195);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const largestPrimeFactor = (number) => {
|
||||
let largestFactor = number;
|
||||
|
||||
for (let i = 2; i <= Math.sqrt(largestFactor); i++) {
|
||||
if (!(largestFactor % i)) {
|
||||
let factor = largestFactor / i;
|
||||
let candidate = largestPrimeFactor(factor);
|
||||
|
||||
return i > candidate ? i : candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return largestFactor;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 5900f38a1000cf542c50fe9d
|
||||
title: 'Problem 30: Digit n powers'
|
||||
challengeType: 1
|
||||
forumTopicId: 301953
|
||||
dashedName: problem-30-digit-n-powers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
|
||||
|
||||
<div style='margin-left: 4em;'>
|
||||
1634 = 1<sup>4</sup> + 6<sup>4</sup> + 3<sup>4</sup> + 4<sup>4</sup><br>
|
||||
8208 = 8<sup>4</sup> + 2<sup>4</sup> + 0<sup>4</sup> + 8<sup>4</sup><br>
|
||||
9474 = 9<sup>4</sup> + 4<sup>4</sup> + 7<sup>4</sup> + 4<sup>4</sup><br>
|
||||
</div>
|
||||
|
||||
As 1 = 1<sup>4</sup> is not a sum it is not included.
|
||||
|
||||
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
|
||||
|
||||
Find the sum of all the numbers that can be written as the sum of `n` powers of their digits.
|
||||
|
||||
# --hints--
|
||||
|
||||
`digitnPowers(2)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof digitnPowers(2) === 'number');
|
||||
```
|
||||
|
||||
`digitnPowers(2)` should return 0.
|
||||
|
||||
```js
|
||||
assert(digitnPowers(2) == 0);
|
||||
```
|
||||
|
||||
`digitnPowers(3)` should return 1301.
|
||||
|
||||
```js
|
||||
assert(digitnPowers(3) == 1301);
|
||||
```
|
||||
|
||||
`digitnPowers(4)` should return 19316.
|
||||
|
||||
```js
|
||||
assert(digitnPowers(4) == 19316);
|
||||
```
|
||||
|
||||
`digitnPowers(5)` should return 443839.
|
||||
|
||||
```js
|
||||
assert(digitnPowers(5) == 443839);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function digitnPowers(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
digitnPowers(5);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 5900f38b1000cf542c50fe9e
|
||||
title: 'Problem 31: Coin sums'
|
||||
challengeType: 1
|
||||
forumTopicId: 301965
|
||||
dashedName: problem-31-coin-sums
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
|
||||
|
||||
<div style='margin-left: 4em;'>1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).</div>
|
||||
|
||||
It is possible to make £2 in the following way:
|
||||
|
||||
<div style='margin-left: 4em;'>1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p</div>
|
||||
|
||||
How many different ways can `n` pence be made using any number of coins?
|
||||
|
||||
# --hints--
|
||||
|
||||
`coinSums(50)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof coinSums(50) === 'number');
|
||||
```
|
||||
|
||||
`coinSums(50)` should return 451.
|
||||
|
||||
```js
|
||||
assert(coinSums(50) == 451);
|
||||
```
|
||||
|
||||
`coinSums(100)` should return 4563.
|
||||
|
||||
```js
|
||||
assert(coinSums(100) == 4563);
|
||||
```
|
||||
|
||||
`coinSums(150)` should return 21873.
|
||||
|
||||
```js
|
||||
assert(coinSums(150) == 21873);
|
||||
```
|
||||
|
||||
`coinSums(200)` should return 73682.
|
||||
|
||||
```js
|
||||
assert(coinSums(200) == 73682);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function coinSums(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
coinSums(200);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const coinSums = (n) => {
|
||||
const getWays = (n, m=8, c=[1, 2, 5, 10, 20, 50, 100, 200]) => {
|
||||
if (n === 0) return 1;
|
||||
if (m === 0 || n < 0) return 0;
|
||||
return getWays(n - c[m - 1], m, c) + getWays(n, m - 1, c);
|
||||
};
|
||||
return getWays(n);
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
id: 5900f38c1000cf542c50fe9f
|
||||
title: 'Problem 32: Pandigital products'
|
||||
challengeType: 1
|
||||
forumTopicId: 301976
|
||||
dashedName: problem-32-pandigital-products
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We shall say that an `n`-digit number is pandigital if it makes use of all the digits 1 to `n` exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
|
||||
|
||||
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
|
||||
|
||||
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through `n` pandigital.
|
||||
|
||||
**Hint:** Some products can be obtained in more than one way so be sure to only include it once in your sum.
|
||||
|
||||
# --hints--
|
||||
|
||||
`pandigitalProducts(4)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof pandigitalProducts(4) === 'number');
|
||||
```
|
||||
|
||||
`pandigitalProducts(4)` should return `12`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pandigitalProducts(4), 12);
|
||||
```
|
||||
|
||||
`pandigitalProducts(6)` should return `162`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pandigitalProducts(6), 162);
|
||||
```
|
||||
|
||||
`pandigitalProducts(7)` should return `0`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pandigitalProducts(7), 0);
|
||||
```
|
||||
|
||||
`pandigitalProducts(8)` should return `13458`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pandigitalProducts(8), 13458);
|
||||
```
|
||||
|
||||
`pandigitalProducts(9)` should return `45228`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pandigitalProducts(9), 45228);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function pandigitalProducts(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
pandigitalProducts(4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function pandigitalProducts(n) {
|
||||
function is1toNPandigital(n, digitStr) {
|
||||
// check if length is n
|
||||
if (digitStr.length !== n) {
|
||||
return false;
|
||||
}
|
||||
// check if pandigital
|
||||
for (let i = digitStr.length; i > 0; i--) {
|
||||
if (digitStr.indexOf(i.toString()) === -1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function concatenateNums(...numbers) {
|
||||
let digitStr = '';
|
||||
for (let i = 0; i < numbers.length; i++) {
|
||||
digitStr += numbers[i].toString();
|
||||
}
|
||||
return digitStr;
|
||||
}
|
||||
|
||||
const pandigitalNums = [];
|
||||
const limit = 10 ** Math.floor(n / 2) - 1;
|
||||
let sum = 0;
|
||||
for (let mult1 = 2; mult1 < limit; mult1++) {
|
||||
for (let mult2 = 2; mult2 < limit; mult2++) {
|
||||
const product = mult1 * mult2;
|
||||
const concatenated = concatenateNums(mult1, mult2, product);
|
||||
if (concatenated.length > n) {
|
||||
break;
|
||||
} else if (concatenated.length < n) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
is1toNPandigital(n, concatenated) &&
|
||||
!pandigitalNums.includes(product)
|
||||
) {
|
||||
pandigitalNums.push(product);
|
||||
sum += product;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 5900f38d1000cf542c50fea0
|
||||
title: 'Problem 33: Digit cancelling fractions'
|
||||
challengeType: 1
|
||||
forumTopicId: 301987
|
||||
dashedName: problem-33-digit-cancelling-fractions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The fraction <sup>49</sup>/<sub>98</sub> is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that <sup>49</sup>/<sub>98</sub> = <sup>4</sup>/<sub>8</sub>, which is correct, is obtained by cancelling the 9s.
|
||||
|
||||
We shall consider fractions like, <sup>30</sup>/<sub>50</sub> = <sup>3</sup>/<sub>5</sub>, to be trivial examples.
|
||||
|
||||
There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.
|
||||
|
||||
If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`digitCancellingFractions()` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof digitCancellingFractions() === 'number');
|
||||
```
|
||||
|
||||
`digitCancellingFractions()` should return 100.
|
||||
|
||||
```js
|
||||
assert.strictEqual(digitCancellingFractions(), 100);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function digitCancellingFractions() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
digitCancellingFractions();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function digitCancellingFractions() {
|
||||
function isCurious(numerator, denominator) {
|
||||
const fraction = numerator / denominator;
|
||||
const numString = numerator.toString();
|
||||
const denString = denominator.toString();
|
||||
|
||||
if (numString[1] === '0' && denString[1] === '0') {
|
||||
// trivial
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < 2; i++) {
|
||||
for (let j = 0; j < 2; j++) {
|
||||
if (numString[i] === denString[j]) {
|
||||
const newNum = parseInt(numString[1 - i], 10);
|
||||
const newDen = parseInt(denString[1 - j], 10);
|
||||
if (newNum / newDen === fraction) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function findLargestDivisor(a, b) {
|
||||
let gcd = a > b ? b : a;
|
||||
while (gcd > 1) {
|
||||
if (a % gcd === 0 && b % gcd === 0) {
|
||||
return gcd;
|
||||
}
|
||||
gcd--;
|
||||
}
|
||||
return gcd;
|
||||
}
|
||||
|
||||
function simplifyFraction(numerator, denominator) {
|
||||
const divisor = findLargestDivisor(numerator, denominator);
|
||||
return [numerator / divisor, denominator / divisor];
|
||||
}
|
||||
|
||||
let multipleNumerator = 1;
|
||||
let multipleDenominator = 1;
|
||||
|
||||
for (let denominator = 11; denominator < 100; denominator++) {
|
||||
for (let numerator = 10; numerator < denominator; numerator++) {
|
||||
if (isCurious(numerator, denominator)) {
|
||||
multipleNumerator *= numerator;
|
||||
multipleDenominator *= denominator;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return simplifyFraction(multipleNumerator, multipleDenominator)[1];
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
id: 5900f38e1000cf542c50fea1
|
||||
title: 'Problem 34: Digit factorials'
|
||||
challengeType: 1
|
||||
forumTopicId: 301998
|
||||
dashedName: problem-34-digit-factorials
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
|
||||
|
||||
Find the numbers and the sum of the numbers which are equal to the sum of the factorial of their digits.
|
||||
|
||||
**Note:** as 1! = 1 and 2! = 2 are not sums they are not included.
|
||||
|
||||
# --hints--
|
||||
|
||||
`digitFactorial()` should return an object.
|
||||
|
||||
```js
|
||||
assert.typeOf(digitFactorial(), 'object');
|
||||
```
|
||||
|
||||
`digitFactorial()` should return { sum: 40730, numbers: [145, 40585] }.
|
||||
|
||||
```js
|
||||
assert.deepEqual(digitFactorial(), { sum: 40730, numbers: [145, 40585] });
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function digitFactorial() {
|
||||
|
||||
var sum = 0;
|
||||
var numbers = [];
|
||||
return { sum, numbers };
|
||||
}
|
||||
|
||||
digitFactorial();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
@@ -0,0 +1,132 @@
|
||||
---
|
||||
id: 5900f38f1000cf542c50fea2
|
||||
title: 'Problem 35: Circular primes'
|
||||
challengeType: 1
|
||||
forumTopicId: 302009
|
||||
dashedName: problem-35-circular-primes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
|
||||
|
||||
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
|
||||
|
||||
How many circular primes are there below `n`, whereas 100 ≤ `n` ≤ 1000000?
|
||||
|
||||
**Note:**
|
||||
|
||||
Circular primes individual rotation can exceed `n`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`circularPrimes(100)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof circularPrimes(100) === 'number');
|
||||
```
|
||||
|
||||
`circularPrimes(100)` should return 13.
|
||||
|
||||
```js
|
||||
assert(circularPrimes(100) == 13);
|
||||
```
|
||||
|
||||
`circularPrimes(100000)` should return 43.
|
||||
|
||||
```js
|
||||
assert(circularPrimes(100000) == 43);
|
||||
```
|
||||
|
||||
`circularPrimes(250000)` should return 45.
|
||||
|
||||
```js
|
||||
assert(circularPrimes(250000) == 45);
|
||||
```
|
||||
|
||||
`circularPrimes(500000)` should return 49.
|
||||
|
||||
```js
|
||||
assert(circularPrimes(500000) == 49);
|
||||
```
|
||||
|
||||
`circularPrimes(750000)` should return 49.
|
||||
|
||||
```js
|
||||
assert(circularPrimes(750000) == 49);
|
||||
```
|
||||
|
||||
`circularPrimes(1000000)` should return 55.
|
||||
|
||||
```js
|
||||
assert(circularPrimes(1000000) == 55);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function circularPrimes(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
circularPrimes(1000000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function rotate(n) {
|
||||
if (n.length == 1) return n;
|
||||
return n.slice(1) + n[0];
|
||||
}
|
||||
|
||||
function circularPrimes(n) {
|
||||
// Nearest n < 10^k
|
||||
const bound = 10 ** Math.ceil(Math.log10(n));
|
||||
const primes = [0, 0, 2];
|
||||
let count = 0;
|
||||
|
||||
// Making primes array
|
||||
for (let i = 4; i <= bound; i += 2) {
|
||||
primes.push(i - 1);
|
||||
primes.push(0);
|
||||
}
|
||||
|
||||
// Getting upperbound
|
||||
const upperBound = Math.ceil(Math.sqrt(bound));
|
||||
|
||||
// Setting other non-prime numbers to 0
|
||||
for (let i = 3; i < upperBound; i += 2) {
|
||||
if (primes[i]) {
|
||||
for (let j = i * i; j < bound; j += i) {
|
||||
primes[j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Iterating through the array
|
||||
for (let i = 2; i < n; i++) {
|
||||
if (primes[i]) {
|
||||
let curr = String(primes[i]);
|
||||
let tmp = 1; // tmp variable to hold the no of rotations
|
||||
for (let x = rotate(curr); x != curr; x = rotate(x)) {
|
||||
if (x > n && primes[x]) {
|
||||
continue;
|
||||
}
|
||||
else if (!primes[x]) {
|
||||
// If the rotated value is 0 then it isn't a circular prime, break the loop
|
||||
tmp = 0;
|
||||
break;
|
||||
}
|
||||
tmp++;
|
||||
primes[x] = 0;
|
||||
}
|
||||
count += tmp;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 5900f3901000cf542c50fea3
|
||||
title: 'Problem 36: Double-base palindromes'
|
||||
challengeType: 1
|
||||
forumTopicId: 302020
|
||||
dashedName: problem-36-double-base-palindromes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The decimal number, 585 = 1001001001<sub>2</sub> (binary), is palindromic in both bases.
|
||||
|
||||
Find the sum of all numbers, less than `n`, whereas 1000 ≤ `n` ≤ 1000000, which are palindromic in base 10 and base 2.
|
||||
|
||||
(Please note that the palindromic number, in either base, may not include leading zeros.)
|
||||
|
||||
# --hints--
|
||||
|
||||
`doubleBasePalindromes(1000)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof doubleBasePalindromes(1000) === 'number');
|
||||
```
|
||||
|
||||
`doubleBasePalindromes(1000)` should return 1772.
|
||||
|
||||
```js
|
||||
assert(doubleBasePalindromes(1000) == 1772);
|
||||
```
|
||||
|
||||
`doubleBasePalindromes(50000)` should return 105795.
|
||||
|
||||
```js
|
||||
assert(doubleBasePalindromes(50000) == 105795);
|
||||
```
|
||||
|
||||
`doubleBasePalindromes(500000)` should return 286602.
|
||||
|
||||
```js
|
||||
assert(doubleBasePalindromes(500000) == 286602);
|
||||
```
|
||||
|
||||
`doubleBasePalindromes(1000000)` should return 872187.
|
||||
|
||||
```js
|
||||
assert(doubleBasePalindromes(1000000) == 872187);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function doubleBasePalindromes(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
doubleBasePalindromes(1000000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 5900f3911000cf542c50fea4
|
||||
title: 'Problem 37: Truncatable primes'
|
||||
challengeType: 1
|
||||
forumTopicId: 302031
|
||||
dashedName: problem-37-truncatable-primes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
|
||||
|
||||
Find the sum of the only `n` (8 ≤ `n` ≤ 11) primes that are both truncatable from left to right and right to left.
|
||||
|
||||
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
|
||||
|
||||
# --hints--
|
||||
|
||||
`truncatablePrimes(8)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof truncatablePrimes(8) === 'number');
|
||||
```
|
||||
|
||||
`truncatablePrimes(8)` should return 1986.
|
||||
|
||||
```js
|
||||
assert(truncatablePrimes(8) == 1986);
|
||||
```
|
||||
|
||||
`truncatablePrimes(9)` should return 5123.
|
||||
|
||||
```js
|
||||
assert(truncatablePrimes(9) == 5123);
|
||||
```
|
||||
|
||||
`truncatablePrimes(10)` should return 8920.
|
||||
|
||||
```js
|
||||
assert(truncatablePrimes(10) == 8920);
|
||||
```
|
||||
|
||||
`truncatablePrimes(11)` should return 748317.
|
||||
|
||||
```js
|
||||
assert(truncatablePrimes(11) == 748317);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function truncatablePrimes(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
truncatablePrimes(11);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
@@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 5900f3931000cf542c50fea5
|
||||
title: 'Problem 38: Pandigital multiples'
|
||||
challengeType: 1
|
||||
forumTopicId: 302042
|
||||
dashedName: problem-38-pandigital-multiples
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Take the number 192 and multiply it by each of 1, 2, and 3:
|
||||
|
||||
$$\begin{align} 192 × 1 = 192\\\\
|
||||
192 × 2 = 384\\\\ 192 × 3 = 576\\\\
|
||||
\end{align}$$
|
||||
|
||||
By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1, 2, 3).
|
||||
|
||||
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1, 2, 3, 4, 5).
|
||||
|
||||
What is the largest 1 to `k` pandigital `k`-digit number that can be formed as the concatenated product of an integer with (1, 2, ..., `n`) where `n` > 1?
|
||||
|
||||
# --hints--
|
||||
|
||||
`pandigitalMultiples(8)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof pandigitalMultiples(8) === 'number');
|
||||
```
|
||||
|
||||
`pandigitalMultiples(8)` should return `78156234`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pandigitalMultiples(8), 78156234);
|
||||
```
|
||||
|
||||
`pandigitalMultiples(9)` should return `932718654`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pandigitalMultiples(9), 932718654);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function pandigitalMultiples(k) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
pandigitalMultiples(8);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function pandigitalMultiples(k) {
|
||||
function getKDigitConcatenatedProduct(num, k) {
|
||||
// returns false if concatenated product is not k digits
|
||||
let concatenatedProduct = num.toString();
|
||||
for (let i = 2; concatenatedProduct.length < k; i++) {
|
||||
concatenatedProduct += num * i;
|
||||
}
|
||||
return concatenatedProduct.length === k ? concatenatedProduct : false;
|
||||
}
|
||||
|
||||
function is1toKPandigital(num, k) {
|
||||
const numStr = num.toString();
|
||||
|
||||
// check if length is not k
|
||||
if (numStr.length !== k) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check if pandigital
|
||||
for (let i = k; i > 0; i--) {
|
||||
if (numStr.indexOf(i.toString()) === -1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
let largestNum = 0;
|
||||
for (let i = 10 ** Math.floor(k / 2) + 1; i >= 1; i--) {
|
||||
const concatenatedProduct = getKDigitConcatenatedProduct(i, k);
|
||||
if (is1toKPandigital(concatenatedProduct, k)) {
|
||||
const number = parseInt(concatenatedProduct, 10);
|
||||
if (number > largestNum) {
|
||||
largestNum = number;
|
||||
}
|
||||
}
|
||||
}
|
||||
return largestNum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 5900f3931000cf542c50fea6
|
||||
title: 'Problem 39: Integer right triangles'
|
||||
challengeType: 1
|
||||
forumTopicId: 302054
|
||||
dashedName: problem-39-integer-right-triangles
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If `p` is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
|
||||
|
||||
{20,48,52}, {24,45,51}, {30,40,50}
|
||||
|
||||
For which value of `p` ≤ `n`, is the number of solutions maximized?
|
||||
|
||||
# --hints--
|
||||
|
||||
`intRightTriangles(500)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof intRightTriangles(500) === 'number');
|
||||
```
|
||||
|
||||
`intRightTriangles(500)` should return 420.
|
||||
|
||||
```js
|
||||
assert(intRightTriangles(500) == 420);
|
||||
```
|
||||
|
||||
`intRightTriangles(800)` should return 720.
|
||||
|
||||
```js
|
||||
assert(intRightTriangles(800) == 720);
|
||||
```
|
||||
|
||||
`intRightTriangles(900)` should return 840.
|
||||
|
||||
```js
|
||||
assert(intRightTriangles(900) == 840);
|
||||
```
|
||||
|
||||
`intRightTriangles(1000)` should return 840.
|
||||
|
||||
```js
|
||||
assert(intRightTriangles(1000) == 840);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function intRightTriangles(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
intRightTriangles(500);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// Original idea for this solution came from
|
||||
// https://www.xarg.org/puzzle/project-euler/problem-39/
|
||||
|
||||
function intRightTriangles(n) {
|
||||
// store the number of triangles with a given perimeter
|
||||
let triangles = {};
|
||||
// a is the shortest side
|
||||
for (let a = 3; a < n / 3; a++)
|
||||
// o is the opposite side and is at least as long as a
|
||||
for (let o = a; o < n / 2; o++) {
|
||||
let h = Math.sqrt(a * a + o * o); // hypotenuse
|
||||
let p = a + o + h; // perimeter
|
||||
if ((h % 1) === 0 && p <= n) {
|
||||
triangles[p] = (triangles[p] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
let max = 0, maxp = null;
|
||||
for (let p in triangles) {
|
||||
if (max < triangles[p]) {
|
||||
max = triangles[p];
|
||||
maxp = parseInt(p);
|
||||
}
|
||||
}
|
||||
return maxp;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: 5900f3701000cf542c50fe83
|
||||
title: 'Problem 4: Largest palindrome product'
|
||||
challengeType: 1
|
||||
forumTopicId: 302065
|
||||
dashedName: problem-4-largest-palindrome-product
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
|
||||
|
||||
Find the largest palindrome made from the product of two `n`-digit numbers.
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestPalindromeProduct(2)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof largestPalindromeProduct(2) === 'number');
|
||||
```
|
||||
|
||||
`largestPalindromeProduct(2)` should return 9009.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPalindromeProduct(2), 9009);
|
||||
```
|
||||
|
||||
`largestPalindromeProduct(3)` should return 906609.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestPalindromeProduct(3), 906609);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function largestPalindromeProduct(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
largestPalindromeProduct(3);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const largestPalindromeProduct = (digit)=>{
|
||||
let start = 1;
|
||||
let end = Number(`1e${digit}`) - 1;
|
||||
let palindrome = [];
|
||||
for(let i=start;i<=end;i++){
|
||||
for(let j=start;j<=end;j++){
|
||||
let product = i*j;
|
||||
let palindromeRegex = /\b(\d)(\d?)(\d?).?\3\2\1\b/gi;
|
||||
palindromeRegex.test(product) && palindrome.push(product);
|
||||
}
|
||||
}
|
||||
return Math.max(...palindrome);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 5900f3941000cf542c50fea7
|
||||
title: 'Problem 40: Champernowne''s constant'
|
||||
challengeType: 1
|
||||
forumTopicId: 302066
|
||||
dashedName: problem-40-champernownes-constant
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
An irrational decimal fraction is created by concatenating the positive integers:
|
||||
|
||||
0.12345678910**1**112131415161718192021...
|
||||
|
||||
It can be seen that the 12<sup>th</sup> digit of the fractional part is 1.
|
||||
|
||||
If *d<sub>n</sub>* represents the *n*<sup>th</sup> digit of the fractional part, find the value of the following expression.
|
||||
|
||||
d<sub>1</sub> × d<sub>10</sub> × d<sub>100</sub> × d<sub>1000</sub> × d<sub>10000</sub> × d<sub>100000</sub> × d<sub>1000000</sub>
|
||||
|
||||
# --hints--
|
||||
|
||||
`champernownesConstant(100)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof champernownesConstant(100) === 'number');
|
||||
```
|
||||
|
||||
`champernownesConstant(100)` should return 5.
|
||||
|
||||
```js
|
||||
assert.strictEqual(champernownesConstant(100), 5);
|
||||
```
|
||||
|
||||
`champernownesConstant(1000)` should return 15.
|
||||
|
||||
```js
|
||||
assert.strictEqual(champernownesConstant(1000), 15);
|
||||
```
|
||||
|
||||
`champernownesConstant(1000000)` should return 210.
|
||||
|
||||
```js
|
||||
assert.strictEqual(champernownesConstant(1000000), 210);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function champernownesConstant(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
champernownesConstant(100);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function champernownesConstant(n) {
|
||||
let fractionalPart = '';
|
||||
for (let i = 0; fractionalPart.length <= n; i++) {
|
||||
fractionalPart += i.toString();
|
||||
}
|
||||
|
||||
let product = 1;
|
||||
for (let i = 0; i < n.toString().length; i++) {
|
||||
const index = 10 ** i;
|
||||
product *= parseInt(fractionalPart[index], 10);
|
||||
}
|
||||
|
||||
return product;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
id: 5900f3951000cf542c50fea8
|
||||
title: 'Problem 41: Pandigital prime'
|
||||
challengeType: 1
|
||||
forumTopicId: 302078
|
||||
dashedName: problem-41-pandigital-prime
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We shall say that an `n`-digit number is pandigital if it makes use of all the digits 1 to `n` exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
|
||||
|
||||
What is the largest `n`-length digit pandigital prime that exists?
|
||||
|
||||
# --hints--
|
||||
|
||||
`pandigitalPrime(4)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof pandigitalPrime(4) === 'number');
|
||||
```
|
||||
|
||||
`pandigitalPrime(4)` should return 4231.
|
||||
|
||||
```js
|
||||
assert(pandigitalPrime(4) == 4231);
|
||||
```
|
||||
|
||||
`pandigitalPrime(7)` should return 7652413.
|
||||
|
||||
```js
|
||||
assert(pandigitalPrime(7) == 7652413);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function pandigitalPrime(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
pandigitalPrime(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function pandigitalPrime(n) {
|
||||
function isPrime(num) {
|
||||
for (let i = 2, s = Math.sqrt(num); i <= s; i++) {
|
||||
if (num % i === 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return num !== 1;
|
||||
}
|
||||
|
||||
function getPermutations(n) {
|
||||
if (n === 1) {
|
||||
permutations.push(digitsArr.join(''));
|
||||
} else {
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
getPermutations(n - 1);
|
||||
// swap(n % 2 === 0 ? i : 0, n - 1);
|
||||
if (n % 2 === 0) {
|
||||
swap(i, n - 1);
|
||||
} else {
|
||||
swap(0, n - 1);
|
||||
}
|
||||
}
|
||||
getPermutations(n - 1);
|
||||
}
|
||||
}
|
||||
function swap(x, y) {
|
||||
let temp = digitsArr[x];
|
||||
digitsArr[x] = digitsArr[y];
|
||||
digitsArr[y] = temp;
|
||||
}
|
||||
let max = 0;
|
||||
let permutations = [];
|
||||
let digitsArr;
|
||||
let pandigitalNum = '';
|
||||
|
||||
for (let max = n; max > 0; max--) {
|
||||
pandigitalNum += max;
|
||||
}
|
||||
|
||||
for (let i = 0; i < pandigitalNum.length; i++) {
|
||||
if (max > 0) {
|
||||
break;
|
||||
} else {
|
||||
permutations = [];
|
||||
const currMax = pandigitalNum.slice(i);
|
||||
digitsArr = currMax.split('');
|
||||
getPermutations(digitsArr.length);
|
||||
|
||||
// sort permutations in descending order
|
||||
permutations.sort(function(a, b) {
|
||||
return b - a;
|
||||
});
|
||||
|
||||
for (let perm of permutations) {
|
||||
const thisPerm = parseInt(perm);
|
||||
if (isPrime(thisPerm)) {
|
||||
max = thisPerm;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return max;
|
||||
}
|
||||
```
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,126 @@
|
||||
---
|
||||
id: 5900f3971000cf542c50feaa
|
||||
title: 'Problem 43: Sub-string divisibility'
|
||||
challengeType: 1
|
||||
forumTopicId: 302100
|
||||
dashedName: problem-43-sub-string-divisibility
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.
|
||||
|
||||
Let $d_1$ be the $1^{st}$ digit, $d_2$ be the $2^{nd}$ digit, and so on. In this way, we note the following:
|
||||
|
||||
- ${d_2}{d_3}{d_4} = 406$ is divisible by 2
|
||||
- ${d_3}{d_4}{d_5} = 063$ is divisible by 3
|
||||
- ${d_4}{d_5}{d_6} = 635$ is divisible by 5
|
||||
- ${d_5}{d_6}{d_7} = 357$ is divisible by 7
|
||||
- ${d_6}{d_7}{d_8} = 572$ is divisible by 11
|
||||
- ${d_7}{d_8}{d_9} = 728$ is divisible by 13
|
||||
- ${d_8}{d_9}{d_{10}} = 289$ is divisible by 17
|
||||
|
||||
Find the sum of all 0 to `n` pandigital numbers with sub-strings fulfilling `n - 2` of these divisibility properties.
|
||||
|
||||
**Note:** Pandigital numbers starting with `0` are to be considered in the result.
|
||||
|
||||
# --hints--
|
||||
|
||||
`substringDivisibility(5)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof substringDivisibility(5) === 'number');
|
||||
```
|
||||
|
||||
`substringDivisibility(5)` should return `12444480`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(substringDivisibility(5), 12444480)
|
||||
```
|
||||
|
||||
`substringDivisibility(7)` should return `1099210170`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(substringDivisibility(7), 1099210170)
|
||||
```
|
||||
|
||||
`substringDivisibility(8)` should return `1113342912`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(substringDivisibility(8), 1113342912)
|
||||
```
|
||||
|
||||
`substringDivisibility(9)` should return `16695334890`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(substringDivisibility(9), 16695334890)
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function substringDivisibility(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
substringDivisibility(5);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function substringDivisibility(n) {
|
||||
function isSubDivisable(digits) {
|
||||
const factors = [2, 3, 5, 7, 11, 13, 17];
|
||||
|
||||
for (let i = 1; i < digits.length - 2; i++) {
|
||||
const subNumber = digits[i] * 100 + digits[i + 1] * 10 + digits[i + 2];
|
||||
if (subNumber % factors[i - 1] !== 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function heapsPermutations(k, digits, conditionCheck, results) {
|
||||
if (k === 1) {
|
||||
if (conditionCheck(digits)) {
|
||||
const number = parseInt(digits.join(''), 10);
|
||||
results.push(number);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
heapsPermutations(k - 1, digits, conditionCheck, results);
|
||||
|
||||
for (let i = 0; i < k - 1; i++) {
|
||||
if (k % 2 === 0) {
|
||||
[digits[i], digits[k - 1]] = [digits[k - 1], digits[i]];
|
||||
} else {
|
||||
[digits[0], digits[k - 1]] = [digits[k - 1], digits[0]];
|
||||
}
|
||||
heapsPermutations(k - 1, digits, conditionCheck, results);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedDigits = [...new Array(n + 1).keys()];
|
||||
const divisablePandigitals = [];
|
||||
heapsPermutations(
|
||||
allowedDigits.length,
|
||||
allowedDigits,
|
||||
isSubDivisable,
|
||||
divisablePandigitals
|
||||
);
|
||||
|
||||
let sum = 0;
|
||||
for (let i = 0; i < divisablePandigitals.length; i++) {
|
||||
sum += divisablePandigitals[i];
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 5900f3981000cf542c50feab
|
||||
title: 'Problem 44: Pentagon numbers'
|
||||
challengeType: 1
|
||||
forumTopicId: 302111
|
||||
dashedName: problem-44-pentagon-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Pentagonal numbers are generated by the formula, P<sub>n</sub>=`n`(3`n`−1)/2. The first ten pentagonal numbers are:
|
||||
|
||||
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
|
||||
|
||||
It can be seen that P<sub>4</sub> + P<sub>7</sub> = 22 + 70 = 92 = P<sub>8</sub>. However, their difference, 70 − 22 = 48, is not pentagonal.
|
||||
|
||||
Find the pair of pentagonal numbers, P<sub>j</sub> and P<sub>k</sub>, for which their sum and difference are pentagonal and D = |P<sub>k</sub> − P<sub>j</sub>| is minimized; what is the value of D?
|
||||
|
||||
# --hints--
|
||||
|
||||
`pentagonNumbers()` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof pentagonNumbers() === 'number');
|
||||
```
|
||||
|
||||
`pentagonNumbers()` should return 5482660.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pentagonNumbers(), 5482660);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function pentagonNumbers() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
pentagonNumbers();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function pentagonNumbers() {
|
||||
function isPentagonal(num) {
|
||||
// Formula found by solving pentagonal number
|
||||
// equation for n.
|
||||
const n = (Math.sqrt((24 * num) + 1) + 1) / 6;
|
||||
return n % 1 === 0;
|
||||
}
|
||||
|
||||
function pentagonal(num) {
|
||||
return (num * ((3 * num) - 1)) / 2;
|
||||
}
|
||||
let result;
|
||||
let i = 1;
|
||||
while (!result) {
|
||||
i++;
|
||||
const num1 = (i * ((3 * i) - 1)) / 2; // Pentagonal num formula
|
||||
const minDiff = num1 - (((i - 1) * ((3 * (i - 1)) - 1)) / 2);
|
||||
let j = i - 1;
|
||||
while (j > 0 && !result) {
|
||||
const num2 = (j * ((3 * j) - 1)) / 2;
|
||||
if (isPentagonal(num1 - num2) && isPentagonal(num1 + num2)) {
|
||||
result = num1 - num2;
|
||||
}
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 5900f3991000cf542c50feac
|
||||
title: 'Problem 45: Triangular, pentagonal, and hexagonal'
|
||||
challengeType: 1
|
||||
forumTopicId: 302122
|
||||
dashedName: problem-45-triangular-pentagonal-and-hexagonal
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
|
||||
|
||||
<div style='display: inline-grid; text-align: center; grid-template-columns: 135px 135px 260px; grid-template-rows: auto;'><div>Triangle</div><div>T<sub>n</sub>=<var>n</var>(<var>n</var>+1)/2</div><div>1, 3, 6, 10, 15, ...</div></div>
|
||||
<div style='display: inline-grid; text-align: center; grid-template-columns: 135px 135px 260px; grid-template-rows: auto;'><div>Pentagonal</div><div>P<sub>n</sub>=<var>n</var>(3<var>n</var>−1)/2</div><div>1, 5, 12, 22, 35, ...</div></div>
|
||||
<div style='display: inline-grid; text-align: center; grid-template-columns: 135px 135px 260px; grid-template-rows: auto;'><div>Hexagonal</div><div>H<sub>n</sub>=<var>n</var>(2<var>n</var>−1)</div><div>1, 6, 15, 28, 45, ...</div></div>
|
||||
|
||||
It can be verified that T<sub>285</sub> = P<sub>165</sub> = H<sub>143</sub> = 40755.
|
||||
|
||||
Find the next triangle number that is also pentagonal and hexagonal.
|
||||
|
||||
# --hints--
|
||||
|
||||
`triPentaHexa(40756)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof triPentaHexa(40756) === 'number');
|
||||
```
|
||||
|
||||
`triPentaHexa(40756)` should return 1533776805.
|
||||
|
||||
```js
|
||||
assert.strictEqual(triPentaHexa(40756), 1533776805);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function triPentaHexa(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
triPentaHexa(40756);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function triPentaHexa(n) {
|
||||
function triangular(num) {
|
||||
return (num * (num + 1)) / 2;
|
||||
}
|
||||
|
||||
function isPentagonal(num) {
|
||||
// Formula found by completing the square and
|
||||
// solving for n.
|
||||
const n = (Math.sqrt((24 * num) + 1) + 1) / 6;
|
||||
return n % 1 === 0;
|
||||
}
|
||||
|
||||
function isHexagonal(num) {
|
||||
// Formula found by completing the square and
|
||||
// solving for n.
|
||||
const n = Math.sqrt(0.5 * (num + (1 / 8))) + 0.25;
|
||||
return n % 1 === 0;
|
||||
}
|
||||
|
||||
let iTri = n;
|
||||
let tri;
|
||||
let found = false;
|
||||
while (!found) {
|
||||
iTri++;
|
||||
tri = triangular(iTri);
|
||||
if (isPentagonal(tri) && isHexagonal(tri)) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return tri;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 5900f39a1000cf542c50fead
|
||||
title: 'Problem 46: Goldbach''s other conjecture'
|
||||
challengeType: 1
|
||||
forumTopicId: 302134
|
||||
dashedName: problem-46-goldbachs-other-conjecture
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
|
||||
|
||||
<div style='margin-left: 2em;'>
|
||||
9 = 7 + 2×1<sup>2</sup><br>
|
||||
15 = 7 + 2×2<sup>2</sup><br>
|
||||
21 = 3 + 2×3<sup>2</sup><br>
|
||||
25 = 7 + 2×3<sup>2</sup><br>
|
||||
27 = 19 + 2×2<sup>2</sup><br>
|
||||
33 = 31 + 2×1<sup>2</sup>
|
||||
</div>
|
||||
|
||||
It turns out that the conjecture was false.
|
||||
|
||||
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
|
||||
|
||||
# --hints--
|
||||
|
||||
`goldbachsOtherConjecture()` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof goldbachsOtherConjecture() === 'number');
|
||||
```
|
||||
|
||||
`goldbachsOtherConjecture()` should return 5777.
|
||||
|
||||
```js
|
||||
assert.strictEqual(goldbachsOtherConjecture(), 5777);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function goldbachsOtherConjecture() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
goldbachsOtherConjecture();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function goldbachsOtherConjecture() { function isPrime(num) {
|
||||
if (num < 2) {
|
||||
return false;
|
||||
} else if (num === 2) {
|
||||
return true;
|
||||
}
|
||||
const sqrtOfNum = Math.floor(num ** 0.5);
|
||||
for (let i = 2; i <= sqrtOfNum + 1; i++) {
|
||||
if (num % i === 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function isSquare(num) {
|
||||
return Math.sqrt(num) % 1 === 0;
|
||||
}
|
||||
|
||||
// construct a list of prime numbers
|
||||
const primes = [];
|
||||
for (let i = 2; primes.length < 1000; i++) {
|
||||
if (isPrime(i)) primes.push(i);
|
||||
}
|
||||
|
||||
let num = 3;
|
||||
let answer;
|
||||
while (!answer) {
|
||||
num += 2;
|
||||
if (!isPrime(num)) {
|
||||
let found = false;
|
||||
for (let primeI = 0; primeI < primes.length && !found; primeI++) {
|
||||
const square = (num - primes[primeI]) / 2;
|
||||
if (isSquare(square)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) answer = num;
|
||||
}
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
id: 5900f39c1000cf542c50feae
|
||||
title: 'Problem 47: Distinct primes factors'
|
||||
challengeType: 1
|
||||
forumTopicId: 302145
|
||||
dashedName: problem-47-distinct-primes-factors
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The first two consecutive numbers to have two distinct prime factors are:
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
14 = 2 × 7<br>
|
||||
15 = 3 × 5
|
||||
</div>
|
||||
|
||||
The first three consecutive numbers to have three distinct prime factors are:
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
644 = 2<sup>2</sup> × 7 × 23<br>
|
||||
645 = 3 × 5 × 43<br>
|
||||
646 = 2 × 17 × 19
|
||||
</div>
|
||||
|
||||
Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
|
||||
|
||||
# --hints--
|
||||
|
||||
`distinctPrimeFactors(2, 2)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof distinctPrimeFactors(2, 2) === 'number');
|
||||
```
|
||||
|
||||
`distinctPrimeFactors(2, 2)` should return 14.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPrimeFactors(2, 2), 14);
|
||||
```
|
||||
|
||||
`distinctPrimeFactors(3, 3)` should return 644.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPrimeFactors(3, 3), 644);
|
||||
```
|
||||
|
||||
`distinctPrimeFactors(4, 4)` should return 134043.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPrimeFactors(4, 4), 134043);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function distinctPrimeFactors(targetNumPrimes, targetConsecutive) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
distinctPrimeFactors(4, 4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function distinctPrimeFactors(targetNumPrimes, targetConsecutive) {
|
||||
const primeLimit = targetNumPrimes * targetConsecutive * 10000;
|
||||
const numFactors = Array(primeLimit).fill(0);
|
||||
|
||||
let numConsecutive = 0;
|
||||
for (let i = 2; i < primeLimit; i++) {
|
||||
if (numFactors[i] === targetNumPrimes) {
|
||||
// Current number is composite with target num factors
|
||||
numConsecutive++;
|
||||
if (numConsecutive === targetConsecutive) {
|
||||
return i - numConsecutive + 1;
|
||||
}
|
||||
} else {
|
||||
// Current number is not matching composite
|
||||
numConsecutive = 0;
|
||||
if (numFactors[i] === 0) {
|
||||
// Current number is prime
|
||||
for (let j = i; j < primeLimit; j += i) {
|
||||
numFactors[j]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 5900f39c1000cf542c50feaf
|
||||
title: 'Problem 48: Self powers'
|
||||
challengeType: 1
|
||||
forumTopicId: 302157
|
||||
dashedName: problem-48-self-powers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The series, 1<sup>1</sup> + 2<sup>2</sup> + 3<sup>3</sup> + ... + 10<sup>10</sup> = 10405071317.
|
||||
|
||||
Find the last ten digits of the series, 1<sup>1</sup> + 2<sup>2</sup> + 3<sup>3</sup> + ... + 1000<sup>1000</sup>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`selfPowers(10, 3)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof selfPowers(10, 3) === 'number');
|
||||
```
|
||||
|
||||
`selfPowers(10, 3)` should return 317.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(10, 3), 317);
|
||||
```
|
||||
|
||||
`selfPowers(150, 6)` should return 29045.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(150, 6), 29045);
|
||||
```
|
||||
|
||||
`selfPowers(673, 7)` should return 2473989.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(673, 7), 2473989);
|
||||
```
|
||||
|
||||
`selfPowers(1000, 10)` should return 9110846700.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(1000, 10), 9110846700);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function selfPowers(power, lastDigits) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
selfPowers(1000, 10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function selfPowers(power, lastDigits) {
|
||||
let sum = 0;
|
||||
const modulo = Math.pow(10, lastDigits);
|
||||
|
||||
for (let i = 1; i <= power; i++) {
|
||||
let temp = i;
|
||||
for (let j = 1; j < i; j++) {
|
||||
temp *= i;
|
||||
temp %= modulo;
|
||||
}
|
||||
|
||||
sum += temp;
|
||||
sum %= modulo;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 5900f39d1000cf542c50feb0
|
||||
title: 'Problem 49: Prime permutations'
|
||||
challengeType: 1
|
||||
forumTopicId: 302159
|
||||
dashedName: problem-49-prime-permutations
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
|
||||
|
||||
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
|
||||
|
||||
What 12-digit number do you form by concatenating the three terms in this sequence?
|
||||
|
||||
# --hints--
|
||||
|
||||
`primePermutations()` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof primePermutations() === 'number');
|
||||
```
|
||||
|
||||
`primePermutations()` should return 296962999629.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primePermutations(), 296962999629);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function primePermutations() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
primePermutations();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function primePermutations() {
|
||||
function arePermutations(num1, num2) {
|
||||
const numStr1 = num1.toString();
|
||||
let numStr2 = num2.toString();
|
||||
if (numStr1.length !== numStr2.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < numStr1.length; i++) {
|
||||
const index = numStr2.indexOf(numStr1[i]);
|
||||
if (index === -1) {
|
||||
return false;
|
||||
}
|
||||
numStr2 = numStr2.slice(0, index) + numStr2.slice(index + 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function isPrime(num) {
|
||||
if (num < 2) {
|
||||
return false;
|
||||
} else if (num === 2) {
|
||||
return true;
|
||||
}
|
||||
const sqrtOfNum = Math.floor(num ** 0.5);
|
||||
for (let i = 2; i <= sqrtOfNum + 1; i++) {
|
||||
if (num % i === 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
for (let num1 = 1000; num1 <= 9999; num1++) {
|
||||
const num2 = num1 + 3330;
|
||||
const num3 = num2 + 3330;
|
||||
if (isPrime(num1) && isPrime(num2) && isPrime(num3)) {
|
||||
if (arePermutations(num1, num2) && arePermutations(num1, num3)
|
||||
&& num1 !== 1487) {
|
||||
// concatenate and return numbers
|
||||
return (num1 * 100000000) + (num2 * 10000) + num3;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 5900f3711000cf542c50fe84
|
||||
title: 'Problem 5: Smallest multiple'
|
||||
challengeType: 1
|
||||
forumTopicId: 302160
|
||||
dashedName: problem-5-smallest-multiple
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
|
||||
|
||||
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to `n`?
|
||||
|
||||
# --hints--
|
||||
|
||||
`smallestMult(5)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof smallestMult(5) === 'number');
|
||||
```
|
||||
|
||||
`smallestMult(5)` should return 60.
|
||||
|
||||
```js
|
||||
assert.strictEqual(smallestMult(5), 60);
|
||||
```
|
||||
|
||||
`smallestMult(7)` should return 420.
|
||||
|
||||
```js
|
||||
assert.strictEqual(smallestMult(7), 420);
|
||||
```
|
||||
|
||||
`smallestMult(10)` should return 2520.
|
||||
|
||||
```js
|
||||
assert.strictEqual(smallestMult(10), 2520);
|
||||
```
|
||||
|
||||
`smallestMult(13)` should return 360360.
|
||||
|
||||
```js
|
||||
assert.strictEqual(smallestMult(13), 360360);
|
||||
```
|
||||
|
||||
`smallestMult(20)` should return 232792560.
|
||||
|
||||
```js
|
||||
assert.strictEqual(smallestMult(20), 232792560);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function smallestMult(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
smallestMult(20);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function smallestMult(n){
|
||||
function gcd(a, b) {
|
||||
return b === 0 ? a : gcd(b, a%b); // Euclidean algorithm
|
||||
}
|
||||
|
||||
function lcm(a, b) {
|
||||
return a * b / gcd(a, b);
|
||||
}
|
||||
var result = 1;
|
||||
for(var i = 2; i <= n; i++) {
|
||||
result = lcm(result, i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
id: 5900f39e1000cf542c50feb1
|
||||
title: 'Problem 50: Consecutive prime sum'
|
||||
challengeType: 1
|
||||
forumTopicId: 302161
|
||||
dashedName: problem-50-consecutive-prime-sum
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The prime 41, can be written as the sum of six consecutive primes:
|
||||
|
||||
<div style='text-align: center;'>41 = 2 + 3 + 5 + 7 + 11 + 13</div>
|
||||
|
||||
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
|
||||
|
||||
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
|
||||
|
||||
Which prime, below one-million, can be written as the sum of the most consecutive primes?
|
||||
|
||||
# --hints--
|
||||
|
||||
`consecutivePrimeSum(1000)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof consecutivePrimeSum(1000) === 'number');
|
||||
```
|
||||
|
||||
`consecutivePrimeSum(1000)` should return 953.
|
||||
|
||||
```js
|
||||
assert.strictEqual(consecutivePrimeSum(1000), 953);
|
||||
```
|
||||
|
||||
`consecutivePrimeSum(1000000)` should return 997651.
|
||||
|
||||
```js
|
||||
assert.strictEqual(consecutivePrimeSum(1000000), 997651);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function consecutivePrimeSum(limit) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
consecutivePrimeSum(1000000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
class PrimeSeive {
|
||||
constructor(num) {
|
||||
const seive = Array(Math.floor((num - 1) / 2)).fill(true);
|
||||
const primes = [2];
|
||||
const upper = Math.floor((num - 1) / 2);
|
||||
const sqrtUpper = Math.floor((Math.sqrt(num) - 1) / 2);
|
||||
|
||||
for (let i = 0; i <= sqrtUpper; i++) {
|
||||
if (seive[i]) {
|
||||
// Mark value in seive array
|
||||
const prime = 2 * i + 3;
|
||||
primes.push(prime);
|
||||
// Mark all multiples of this number as false (not prime)
|
||||
const primeSqaredIndex = 2 * i ** 2 + 6 * i + 3;
|
||||
for (let j = primeSqaredIndex; j < upper; j += prime) {
|
||||
seive[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let i = sqrtUpper + 1; i < upper; i++) {
|
||||
if (seive[i]) {
|
||||
primes.push(2 * i + 3);
|
||||
}
|
||||
}
|
||||
|
||||
this._seive = seive;
|
||||
this._primes = primes;
|
||||
}
|
||||
|
||||
isPrime(num) {
|
||||
return num === 2
|
||||
? true
|
||||
: num % 2 === 0
|
||||
? false
|
||||
: this.isOddPrime(num);
|
||||
}
|
||||
|
||||
isOddPrime(num) {
|
||||
return this._seive[(num - 3) / 2];
|
||||
}
|
||||
|
||||
get primes() {
|
||||
return this._primes;
|
||||
}
|
||||
};
|
||||
|
||||
function consecutivePrimeSum(limit) {
|
||||
// Initalize seive
|
||||
const primeSeive = new PrimeSeive(limit);
|
||||
|
||||
// Initalize for longest sum < 100
|
||||
let bestPrime = 41;
|
||||
let bestI = 0;
|
||||
let bestJ = 5;
|
||||
|
||||
// Find longest sum < limit
|
||||
let sumOfCurrRange = 41;
|
||||
let i = 0, j = 5;
|
||||
// -- Loop while current some starting at i is < limit
|
||||
while (sumOfCurrRange < limit) {
|
||||
let currSum = sumOfCurrRange;
|
||||
// -- Loop while pushing j towards end of PRIMES list
|
||||
// keeping sum under limit
|
||||
while (currSum < limit) {
|
||||
if (primeSeive.isPrime(currSum)) {
|
||||
bestPrime = sumOfCurrRange = currSum;
|
||||
bestI = i;
|
||||
bestJ = j;
|
||||
}
|
||||
// -- Increment inner loop
|
||||
j++;
|
||||
currSum += primeSeive.primes[j];
|
||||
}
|
||||
// -- Increment outer loop
|
||||
i++;
|
||||
j = i + (bestJ - bestI);
|
||||
sumOfCurrRange -= primeSeive.primes[i - 1];
|
||||
sumOfCurrRange += primeSeive.primes[j];
|
||||
}
|
||||
// Return
|
||||
return bestPrime;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,140 @@
|
||||
---
|
||||
id: 5900f39f1000cf542c50feb2
|
||||
title: 'Problem 51: Prime digit replacements'
|
||||
challengeType: 1
|
||||
forumTopicId: 302162
|
||||
dashedName: problem-51-prime-digit-replacements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
By replacing the 1st digit of the 2-digit number \*3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
|
||||
|
||||
By replacing the 3rd and 4th digits of 56\*\*3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
|
||||
|
||||
Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an `n` prime value family.
|
||||
|
||||
# --hints--
|
||||
|
||||
`primeDigitReplacements(6)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof primeDigitReplacements(6) === 'number');
|
||||
```
|
||||
|
||||
`primeDigitReplacements(6)` should return `13`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeDigitReplacements(6), 13);
|
||||
```
|
||||
|
||||
`primeDigitReplacements(7)` should return `56003`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeDigitReplacements(7), 56003);
|
||||
```
|
||||
|
||||
`primeDigitReplacements(8)` should return `121313`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeDigitReplacements(8), 121313);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function primeDigitReplacements(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
primeDigitReplacements(6);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
class PrimeSeive {
|
||||
constructor(num) {
|
||||
const seive = Array(Math.floor((num - 1) / 2)).fill(true);
|
||||
const upper = Math.floor((num - 1) / 2);
|
||||
const sqrtUpper = Math.floor((Math.sqrt(num) - 1) / 2);
|
||||
|
||||
for (let i = 0; i <= sqrtUpper; i++) {
|
||||
if (seive[i]) {
|
||||
// Mark value in seive array
|
||||
const prime = 2 * i + 3;
|
||||
// Mark all multiples of this number as false (not prime)
|
||||
const primeSqaredIndex = 2 * i ** 2 + 6 * i + 3;
|
||||
for (let j = primeSqaredIndex; j < upper; j += prime) {
|
||||
seive[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._seive = seive;
|
||||
}
|
||||
|
||||
isPrime(num) {
|
||||
return num === 2
|
||||
? true
|
||||
: num % 2 === 0
|
||||
? false
|
||||
: this.isOddPrime(num);
|
||||
}
|
||||
|
||||
isOddPrime(num) {
|
||||
return this._seive[(num - 3) / 2];
|
||||
}
|
||||
};
|
||||
|
||||
function primeDigitReplacements(n) {
|
||||
const primeSeive = new PrimeSeive(n * n * n * 2000);
|
||||
|
||||
function isNFamily(number, n) {
|
||||
const prime = number.toString();
|
||||
const lastDigit = prime[prime.length - 1];
|
||||
return doesReplacingMakeFamily(prime, '0', n) ||
|
||||
doesReplacingMakeFamily(prime, '2', n) ||
|
||||
(lastDigit !== '1' && doesReplacingMakeFamily(prime, '1', n));
|
||||
}
|
||||
|
||||
function doesReplacingMakeFamily(prime, digitToReplace, family) {
|
||||
let miss = 0;
|
||||
const base = parseInt(
|
||||
prime
|
||||
.split('')
|
||||
.map(digit => digit == digitToReplace ? '0' : digit)
|
||||
.join('')
|
||||
);
|
||||
const replacements = parseInt(
|
||||
prime
|
||||
.split('')
|
||||
.map(digit => digit === digitToReplace ? '1' : '0')
|
||||
.join('')
|
||||
);
|
||||
const start = prime[0] === digitToReplace ? 1 : 0;
|
||||
for (let i = start; i < 10; i++) {
|
||||
const nextNumber = base + i * replacements;
|
||||
if (!isPartOfFamily(nextNumber, prime)) miss++;
|
||||
if (10 - start - miss < family) break;
|
||||
}
|
||||
return 10 - start - miss === family;
|
||||
}
|
||||
|
||||
function isPartOfFamily(number, prime) {
|
||||
return (
|
||||
primeSeive.isPrime(number) && number.toString().length === prime.length
|
||||
);
|
||||
}
|
||||
|
||||
for (let number = 1; number < 125000; number++) {
|
||||
if (primeSeive.isPrime(number) && isNFamily(number, n)) {
|
||||
return number;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
id: 5900f3a01000cf542c50feb3
|
||||
title: 'Problem 52: Permuted multiples'
|
||||
challengeType: 1
|
||||
forumTopicId: 302163
|
||||
dashedName: problem-52-permuted-multiples
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
|
||||
|
||||
Find the smallest positive integer, such that multiplied by integers $\\{2, 3, \ldots, n\\}$, contain the same digits.
|
||||
|
||||
# --hints--
|
||||
|
||||
`permutedMultiples(2)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof permutedMultiples(2) === 'number');
|
||||
```
|
||||
|
||||
`permutedMultiples(2)` should return `125874`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permutedMultiples(2), 125874);
|
||||
```
|
||||
|
||||
`permutedMultiples(6)` should return `142857`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permutedMultiples(6), 142857);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function permutedMultiples(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
permutedMultiples(2);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function permutedMultiples(n) {
|
||||
const isPermutation = (a, b) =>
|
||||
a.length !== b.length
|
||||
? false
|
||||
: a.split('').sort().join() === b.split('').sort().join();
|
||||
|
||||
|
||||
let start = 1;
|
||||
let found = false;
|
||||
let result = 0;
|
||||
|
||||
while (!found) {
|
||||
start *= 10;
|
||||
for (let i = start; i < start * 10 / n; i++) {
|
||||
found = true;
|
||||
for (let j = 2; j <= n; j++) {
|
||||
if (!isPermutation(i + '', j * i + '')) {
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found) {
|
||||
result = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 5900f3a11000cf542c50feb4
|
||||
title: 'Problem 53: Combinatoric selections'
|
||||
challengeType: 1
|
||||
forumTopicId: 302164
|
||||
dashedName: problem-53-combinatoric-selections
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
There are exactly ten ways of selecting three from five, 12345:
|
||||
|
||||
<div style='text-align: center;'>123, 124, 125, 134, 135, 145, 234, 235, 245, and 345</div>
|
||||
|
||||
In combinatorics, we use the notation, $\\displaystyle \\binom 5 3 = 10$
|
||||
|
||||
In general, $\\displaystyle \\binom n r = \\dfrac{n!}{r!(n-r)!}$, where $r \\le n$, $n! = n \\times (n-1) \\times ... \\times 3 \\times 2 \\times 1$, and $0! = 1$.
|
||||
|
||||
It is not until $n = 23$, that a value exceeds one-million: $\\displaystyle \\binom {23} {10} = 1144066$.
|
||||
|
||||
How many, not necessarily distinct, values of $\\displaystyle \\binom n r$ for $1 \\le n \\le 100$, are greater than one-million?
|
||||
|
||||
# --hints--
|
||||
|
||||
`combinatoricSelections(1000)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof combinatoricSelections(1000) === 'number');
|
||||
```
|
||||
|
||||
`combinatoricSelections(1000)` should return 4626.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(1000), 4626);
|
||||
```
|
||||
|
||||
`combinatoricSelections(10000)` should return 4431.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(10000), 4431);
|
||||
```
|
||||
|
||||
`combinatoricSelections(100000)` should return 4255.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(100000), 4255);
|
||||
```
|
||||
|
||||
`combinatoricSelections(1000000)` should return 4075.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(1000000), 4075);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function combinatoricSelections(limit) {
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
combinatoricSelections(1000000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function combinatoricSelections(limit) {
|
||||
const factorial = n =>
|
||||
Array.apply(null, { length: n })
|
||||
.map((_, i) => i + 1)
|
||||
.reduce((p, c) => p * c, 1);
|
||||
|
||||
let result = 0;
|
||||
const nMax = 100;
|
||||
|
||||
for (let n = 1; n <= nMax; n++) {
|
||||
for (let r = 0; r <= n; r++) {
|
||||
if (factorial(n) / (factorial(r) * factorial(n - r)) >= limit)
|
||||
result++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,113 @@
|
||||
---
|
||||
id: 5900f3a31000cf542c50feb6
|
||||
title: 'Problem 55: Lychrel numbers'
|
||||
challengeType: 1
|
||||
forumTopicId: 302166
|
||||
dashedName: problem-55-lychrel-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
|
||||
|
||||
Not all numbers produce palindromes so quickly. For example,
|
||||
|
||||
<div style="margin-left: 4em;">
|
||||
349 + 943 = 1292,<br>
|
||||
1292 + 2921 = 4213<br>
|
||||
4213 + 3124 = 7337<br>
|
||||
</div>
|
||||
|
||||
That is, 349 took three iterations to arrive at a palindrome.
|
||||
|
||||
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
|
||||
|
||||
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
|
||||
|
||||
How many Lychrel numbers are there below `num`?
|
||||
|
||||
**Note:** Wording was modified slightly on 24 April 2007 to emphasize the theoretical nature of Lychrel numbers.
|
||||
|
||||
# --hints--
|
||||
|
||||
`countLychrelNumbers(1000)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof countLychrelNumbers(1000) === 'number');
|
||||
```
|
||||
|
||||
`countLychrelNumbers(1000)` should return 13.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(1000), 13);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(3243)` should return 39.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(3243), 39);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(5000)` should return 76.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(5000), 76);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(7654)` should return 140.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(7654), 140);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(10000)` should return 249.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(10000), 249);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countLychrelNumbers(num) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
countLychrelNumbers(10000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const countLychrelNumbers = (size) => {
|
||||
const numReverse = (num) => {
|
||||
return Number(num.toString().split('').reverse().join(''));
|
||||
};
|
||||
const isPalin = (num) => {
|
||||
if (numReverse(num) === num) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
let total = 0;
|
||||
for (let i = 1; i < size; i++) {
|
||||
let loopCount = 1;
|
||||
let sum = i;
|
||||
while (loopCount < 50) {
|
||||
sum = sum + numReverse(sum);
|
||||
if (isPalin(sum)) {
|
||||
break;
|
||||
} else {
|
||||
loopCount++;
|
||||
}
|
||||
}
|
||||
if (loopCount === 50) {
|
||||
total++;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 5900f3a41000cf542c50feb7
|
||||
title: 'Problem 56: Powerful digit sum'
|
||||
challengeType: 1
|
||||
forumTopicId: 302167
|
||||
dashedName: problem-56-powerful-digit-sum
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A googol ($10^{100}$) is a massive number: one followed by one-hundred zeros; $100^{100}$ is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
|
||||
|
||||
Considering natural numbers of the form, $a^b$, where `a`, `b` < `n`, what is the maximum digital sum?
|
||||
|
||||
# --hints--
|
||||
|
||||
`powerfulDigitSum(3)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof powerfulDigitSum(3) === 'number');
|
||||
```
|
||||
|
||||
`powerfulDigitSum(3)` should return `4`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(3), 4);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(10)` should return `45`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(10), 45);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(50)` should return `406`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(50), 406);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(75)` should return `684`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(75), 684);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(100)` should return `972`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(100), 972);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function powerfulDigitSum(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
powerfulDigitSum(3);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function powerfulDigitSum(n) {
|
||||
function sumDigitsOfPower(numA, numB) {
|
||||
let digitsSum = 0;
|
||||
let number = power(numA, numB);
|
||||
while (number > 0n) {
|
||||
const digit = number % 10n;
|
||||
digitsSum += parseInt(digit, 10);
|
||||
number = number / 10n;
|
||||
}
|
||||
return digitsSum;
|
||||
}
|
||||
|
||||
function power(numA, numB) {
|
||||
let sum = 1n;
|
||||
for (let b = 0; b < numB; b++) {
|
||||
sum = sum * BigInt(numA);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
const limit = n - 1;
|
||||
let maxDigitsSum = 0;
|
||||
for (let a = limit; a > 0; a--) {
|
||||
for (let b = limit; b > 0; b--) {
|
||||
const curDigitSum = sumDigitsOfPower(a, b);
|
||||
if (curDigitSum > maxDigitsSum) {
|
||||
maxDigitsSum = curDigitSum;
|
||||
}
|
||||
}
|
||||
}
|
||||
return maxDigitsSum;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 5900f3a51000cf542c50feb8
|
||||
title: 'Problem 57: Square root convergents'
|
||||
challengeType: 1
|
||||
forumTopicId: 302168
|
||||
dashedName: problem-57-square-root-convergents
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
|
||||
|
||||
<div style='text-align: center;'>$\sqrt 2 =1+ \frac 1 {2+ \frac 1 {2 +\frac 1 {2+ \dots}}}$</div>
|
||||
|
||||
By expanding this for the first four iterations, we get:
|
||||
|
||||
$1 + \\frac 1 2 = \\frac 32 = 1.5$
|
||||
|
||||
$1 + \\frac 1 {2 + \\frac 1 2} = \\frac 7 5 = 1.4$
|
||||
|
||||
$1 + \\frac 1 {2 + \\frac 1 {2+\\frac 1 2}} = \\frac {17}{12} = 1.41666 \\dots$
|
||||
|
||||
$1 + \\frac 1 {2 + \\frac 1 {2+\\frac 1 {2+\\frac 1 2}}} = \\frac {41}{29} = 1.41379 \\dots$
|
||||
|
||||
The next three expansions are $\\frac {99}{70}$, $\\frac {239}{169}$, and $\\frac {577}{408}$, but the eighth expansion, $\\frac {1393}{985}$, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
|
||||
|
||||
In the first `n` expansions, how many fractions contain a numerator with more digits than denominator?
|
||||
|
||||
# --hints--
|
||||
|
||||
`squareRootConvergents(10)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof squareRootConvergents(10) === 'number');
|
||||
```
|
||||
|
||||
`squareRootConvergents(10)` should return 1.
|
||||
|
||||
```js
|
||||
assert.strictEqual(squareRootConvergents(10), 1);
|
||||
```
|
||||
|
||||
`squareRootConvergents(100)` should return 15.
|
||||
|
||||
```js
|
||||
assert.strictEqual(squareRootConvergents(100), 15);
|
||||
```
|
||||
|
||||
`squareRootConvergents(1000)` should return 153.
|
||||
|
||||
```js
|
||||
assert.strictEqual(squareRootConvergents(1000), 153);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function squareRootConvergents(n) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
squareRootConvergents(1000);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function squareRootConvergents(n) {
|
||||
function countDigits(number) {
|
||||
let counter = 0;
|
||||
while (number > 0) {
|
||||
counter++;
|
||||
number = number / 10n;
|
||||
}
|
||||
return counter;
|
||||
}
|
||||
|
||||
// Use BigInt as integer won't handle all cases
|
||||
let numerator = 3n;
|
||||
let denominator = 2n;
|
||||
let moreDigitsInNumerator = 0;
|
||||
|
||||
for (let i = 2; i <= n; i++) {
|
||||
[numerator, denominator] = [
|
||||
numerator + 2n * denominator,
|
||||
denominator + numerator
|
||||
];
|
||||
|
||||
if (countDigits(numerator) > countDigits(denominator)) {
|
||||
moreDigitsInNumerator++;
|
||||
}
|
||||
}
|
||||
return moreDigitsInNumerator;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,105 @@
|
||||
---
|
||||
id: 5900f3a61000cf542c50feb9
|
||||
title: 'Problem 58: Spiral primes'
|
||||
challengeType: 1
|
||||
forumTopicId: 302169
|
||||
dashedName: problem-58-spiral-primes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
|
||||
|
||||
<div style='text-align: center;'>
|
||||
<strong><span style='color: red;'>37</span></strong> 36 35 34 33 32 <strong><span style='color: red;'>31</span></strong><br>
|
||||
38 <strong><span style='color: red;'>17</span></strong> 16 15 14 <strong><span style='color: red;'>13</span></strong> 30<br>
|
||||
39 18 <strong><span style='color: red;'>5</span></strong> 4 <strong><span style='color: red;'>3</span></strong> 12 29<br>
|
||||
40 19 6 1 2 11 28<br>
|
||||
41 20 <strong><span style='color: red;'>7</span></strong> 8 9 10 27<br>
|
||||
42 21 22 23 24 25 26<br>
|
||||
<strong><span style='color: red;'>43</span></strong> 44 45 46 47 48 49<br>
|
||||
</div>
|
||||
|
||||
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
|
||||
|
||||
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the percent of primes along both diagonals first falls below `percent`?
|
||||
|
||||
# --hints--
|
||||
|
||||
`spiralPrimes(50)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof spiralPrimes(50) === 'number');
|
||||
```
|
||||
|
||||
`spiralPrimes(50)` should return `11`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spiralPrimes(50), 11);
|
||||
```
|
||||
|
||||
`spiralPrimes(15)` should return `981`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spiralPrimes(15), 981);
|
||||
```
|
||||
|
||||
`spiralPrimes(10)` should return `26241`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spiralPrimes(10), 26241);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function spiralPrimes(percent) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
spiralPrimes(50);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function spiralPrimes(percent) {
|
||||
function isPrime(n) {
|
||||
if (n <= 3) {
|
||||
return n > 1;
|
||||
} else if (n % 2 === 0 || n % 3 === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 5; i * i <= n; i += 6) {
|
||||
if (n % i === 0 || n % (i + 2) === 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
let totalCount = 1;
|
||||
let primesCount = 0;
|
||||
let curNumber = 1;
|
||||
let curSideLength = 1;
|
||||
let ratio = 1;
|
||||
const wantedRatio = percent / 100;
|
||||
|
||||
while (ratio >= wantedRatio) {
|
||||
curSideLength += 2;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
curNumber += curSideLength - 1;
|
||||
totalCount++;
|
||||
if (i !== 3 && isPrime(curNumber)) {
|
||||
primesCount++;
|
||||
}
|
||||
}
|
||||
ratio = primesCount / totalCount;
|
||||
}
|
||||
return curSideLength;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
id: 5900f3a81000cf542c50feba
|
||||
title: 'Problem 59: XOR decryption'
|
||||
challengeType: 1
|
||||
forumTopicId: 302170
|
||||
dashedName: problem-59-xor-decryption
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (\*) = 42, and lowercase k = 107.
|
||||
|
||||
A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
|
||||
|
||||
For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.
|
||||
|
||||
Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
|
||||
|
||||
Your task has been made easy, as the encryption key consists of three lower case characters. Using `cipher`, an array containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
|
||||
|
||||
# --hints--
|
||||
|
||||
`XORDecryption(cipher)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof XORDecryption(cipher) === 'number');
|
||||
```
|
||||
|
||||
`XORDecryption(cipher)` should return 129448.
|
||||
|
||||
```js
|
||||
assert.strictEqual(XORDecryption(cipher), 129448);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function XORDecryption(arr) {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
const cipher = [
|
||||
36,22,80,0,0,4,23,25,19,17,88,4,4,19,21,11,88,22,23,23,29,69,12,24,0,88,25,11,12,2,10,28,5,6,12,25,10,22,80,10,30,80,10,22,21,69,23,22,69,61,5,9,29,2,66,11,80,8,23,3,17,88,19,0,20,21,7,10,17,17,29,20,69,8,17,21,29,2,22,84,80,71,60,21,69,11,5,8,21,25,22,88,3,0,10,25,0,10,5,8,88,2,0,27,25,21,10,31,6,25,2,16,21,82,69,35,63,11,88,4,13,29,80,22,13,29,22,88,31,3,88,3,0,10,25,0,11,80,10,30,80,23,29,19,12,8,2,10,27,17,9,11,45,95,88,57,69,16,17,19,29,80,23,29,19,0,22,4,9,1,80,3,23,5,11,28,92,69,9,5,12,12,21,69,13,30,0,0,0,0,27,4,0,28,28,28,84,80,4,22,80,0,20,21,2,25,30,17,88,21,29,8,2,0,11,3,12,23,30,69,30,31,23,88,4,13,29,80,0,22,4,12,10,21,69,11,5,8,88,31,3,88,4,13,17,3,69,11,21,23,17,21,22,88,65,69,83,80,84,87,68,69,83,80,84,87,73,69,83,80,84,87,65,83,88,91,69,29,4,6,86,92,69,15,24,12,27,24,69,28,21,21,29,30,1,11,80,10,22,80,17,16,21,69,9,5,4,28,2,4,12,5,23,29,80,10,30,80,17,16,21,69,27,25,23,27,28,0,84,80,22,23,80,17,16,17,17,88,25,3,88,4,13,29,80,17,10,5,0,88,3,16,21,80,10,30,80,17,16,25,22,88,3,0,10,25,0,11,80,12,11,80,10,26,4,4,17,30,0,28,92,69,30,2,10,21,80,12,12,80,4,12,80,10,22,19,0,88,4,13,29,80,20,13,17,1,10,17,17,13,2,0,88,31,3,88,4,13,29,80,6,17,2,6,20,21,69,30,31,9,20,31,18,11,94,69,54,17,8,29,28,28,84,80,44,88,24,4,14,21,69,30,31,16,22,20,69,12,24,4,12,80,17,16,21,69,11,5,8,88,31,3,88,4,13,17,3,69,11,21,23,17,21,22,88,25,22,88,17,69,11,25,29,12,24,69,8,17,23,12,80,10,30,80,17,16,21,69,11,1,16,25,2,0,88,31,3,88,4,13,29,80,21,29,2,12,21,21,17,29,2,69,23,22,69,12,24,0,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,67,80,10,10,80,7,1,80,21,13,4,17,17,30,2,88,4,13,29,80,22,13,29,69,23,22,69,12,24,12,11,80,22,29,2,12,29,3,69,29,1,16,25,28,69,12,31,69,11,92,69,17,4,69,16,17,22,88,4,13,29,80,23,25,4,12,23,80,22,9,2,17,80,70,76,88,29,16,20,4,12,8,28,12,29,20,69,26,9,69,11,80,17,23,80,84,88,31,3,88,4,13,29,80,21,29,2,12,21,21,17,29,2,69,12,31,69,12,24,0,88,20,12,25,29,0,12,21,23,86,80,44,88,7,12,20,28,69,11,31,10,22,80,22,16,31,18,88,4,13,25,4,69,12,24,0,88,3,16,21,80,10,30,80,17,16,25,22,88,3,0,10,25,0,11,80,17,23,80,7,29,80,4,8,0,23,23,8,12,21,17,17,29,28,28,88,65,75,78,68,81,65,67,81,72,70,83,64,68,87,74,70,81,75,70,81,67,80,4,22,20,69,30,2,10,21,80,8,13,28,17,17,0,9,1,25,11,31,80,17,16,25,22,88,30,16,21,18,0,10,80,7,1,80,22,17,8,73,88,17,11,28,80,17,16,21,11,88,4,4,19,25,11,31,80,17,16,21,69,11,1,16,25,2,0,88,2,10,23,4,73,88,4,13,29,80,11,13,29,7,29,2,69,75,94,84,76,65,80,65,66,83,77,67,80,64,73,82,65,67,87,75,72,69,17,3,69,17,30,1,29,21,1,88,0,23,23,20,16,27,21,1,84,80,18,16,25,6,16,80,0,0,0,23,29,3,22,29,3,69,12,24,0,88,0,0,10,25,8,29,4,0,10,80,10,30,80,4,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,86,80,35,23,28,9,23,7,12,22,23,69,25,23,4,17,30,69,12,24,0,88,3,4,21,21,69,11,4,0,8,3,69,26,9,69,15,24,12,27,24,69,49,80,13,25,20,69,25,2,23,17,6,0,28,80,4,12,80,17,16,25,22,88,3,16,21,92,69,49,80,13,25,6,0,88,20,12,11,19,10,14,21,23,29,20,69,12,24,4,12,80,17,16,21,69,11,5,8,88,31,3,88,4,13,29,80,22,29,2,12,29,3,69,73,80,78,88,65,74,73,70,69,83,80,84,87,72,84,88,91,69,73,95,87,77,70,69,83,80,84,87,70,87,77,80,78,88,21,17,27,94,69,25,28,22,23,80,1,29,0,0,22,20,22,88,31,11,88,4,13,29,80,20,13,17,1,10,17,17,13,2,0,88,31,3,88,4,13,29,80,6,17,2,6,20,21,75,88,62,4,21,21,9,1,92,69,12,24,0,88,3,16,21,80,10,30,80,17,16,25,22,88,29,16,20,4,12,8,28,12,29,20,69,26,9,69,65,64,69,31,25,19,29,3,69,12,24,0,88,18,12,9,5,4,28,2,4,12,21,69,80,22,10,13,2,17,16,80,21,23,7,0,10,89,69,23,22,69,12,24,0,88,19,12,10,19,16,21,22,0,10,21,11,27,21,69,23,22,69,12,24,0,88,0,0,10,25,8,29,4,0,10,80,10,30,80,4,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,86,80,36,22,20,69,26,9,69,11,25,8,17,28,4,10,80,23,29,17,22,23,30,12,22,23,69,49,80,13,25,6,0,88,28,12,19,21,18,17,3,0,88,18,0,29,30,69,25,18,9,29,80,17,23,80,1,29,4,0,10,29,12,22,21,69,12,24,0,88,3,16,21,3,69,23,22,69,12,24,0,88,3,16,26,3,0,9,5,0,22,4,69,11,21,23,17,21,22,88,25,11,88,7,13,17,19,13,88,4,13,29,80,0,0,0,10,22,21,11,12,3,69,25,2,0,88,21,19,29,30,69,22,5,8,26,21,23,11,94
|
||||
];
|
||||
|
||||
XORDecryption(cipher);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user