# Учебная практика 2021. Среда 7.07.2021. Федяева Евгения Игоревна.
Присутствовала на онлайн-лекции, решенные задачи защитила.
1. [Playing with digits](https://www.codewars.com/kata/5552101f47fc5178b1000050) 6kyu
Description:
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n.
In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n and p will always be given as strictly positive integers.
Описание:
Некоторые числа обладают забавными свойствами. Например:
89 -> 8¹ + 9² = 89 * 1
695 -> 6² + 9³ + 5⁴ = 1390 = 695 * 2
46288 -> 4³ + 6⁴ + 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Дано положительное целое число n, записанное как abcd ... (a, b, c, d ... цифры) и положительное целое число p
мы хотим найти положительное целое число k, если оно существует, например, сумма цифр n, взятых в последовательные степени p, равна k * n.
Другими словами:
Существует ли целое число k, например: (a ^ p + b ^ (p + 1) + c ^ (p + 2) + d ^ (p + 3) + ...) = n * k
Если это так, мы вернем k, если не вернем -1.
Примечание: n и p всегда будут строго положительными целыми числами.
Решение на С++
```c++=
#include <string>
#include <cmath>
class DigPow
{
public:
static int digPow(int n, int p)
{
std::string tmp = std::to_string(n);
int l = tmp.length();
int sum = 0;
for(int i = 0; i < l; i++)
{
int a = tmp[i] - '0';
sum += pow(a, p++);
}
if(sum%n == 0) return sum/n;
else return -1;
};
};
```
Решение на Java
```java=
public class DigPow
{
public static long digPow(int n, int p)
{
String tmp = Integer.toString(n);
int l = tmp.length();
int sum = 0;
for(int i = 0; i < l; i++)
{
int a = Character.getNumericValue(tmp.charAt(i));
sum += Math.pow(a, p++);
}
if(sum%n == 0) return sum/n;
else return -1;
}
}
```
2. [Primorial Of a Number](https://www.codewars.com/kata/5a99a03e4a6b34bb3c000124) 6kyu
Is similar to factorial of a number, In primorial, not all the natural numbers get multiplied, only prime numbers are multiplied to calculate the primorial of a number. It's denoted with P# and it is the product of the first n prime numbers.
Task
Given a number N , calculate its primorial.
Похож на факториал числа. В изначальном порядке умножаются не все натуральные числа, а только простые числа, чтобы вычислить начальное число. Он обозначается P# и является произведением первых n простых чисел.
Задача
Учитывая число N, вычислите его примор.
Решение на С++
```c++=
#include <cmath>
bool Prime(int n)
{
for (int i = 2; i <= sqrt(n); i++)
if (n%i == 0)
return false;
return true;
}
unsigned long long numPrimorial (unsigned short int number )
{
unsigned long long primorial = 2;
int count = 1, x = 3;
while(count < number)
{
if(Prime(x))
{
primorial *= x;
count++;
}
x += 2;
}
return primorial;
}
```
Решение на Java
```java=
import java.math.BigInteger;
public class Primorial
{
static boolean Prime(int n)
{
for (int i = 2; i <= Math.sqrt(n); i++)
if (n%i == 0)
return false;
return true;
}
public static String numPrimorial(int n)
{
BigInteger primorial = BigInteger.valueOf(2);
int count = 1, x = 3;
while(count < n)
{
if(Prime(x))
{
primorial = primorial.multiply(BigInteger.valueOf(x));
count++;
}
x += 2;
}
return primorial.toString();
}
}
```
3. [Two Sum](https://www.codewars.com/kata/52c31f8e6605bcc646000082) 6kyu
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).
For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.
The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).
Напишите функцию, которая принимает массив чисел (целые числа для тестов) и целевое число. Он должен найти два разных элемента в массиве, которые при сложении дают целевое значение. Затем индексы этих элементов должны быть возвращены в виде кортежа: (index1, index2).
Для целей этого ката некоторые тесты могут иметь несколько ответов; любые действующие решения будут приняты.
Ввод всегда будет действительным (числа будут массивом длиной 2 или больше, и все элементы будут числами; цель всегда будет суммой двух разных элементов из этого массива).
Решение на С++
```c++=
std::pair<std::size_t, std::size_t> two_sum(const std::vector<int>& numbers, int target)
{
int n = numbers.size();
for(int i = 0; i < n - 1; i++)
for(int j = i + 1; j < n; j++)
if(numbers[i] + numbers[j] == target)
return {i, j};
}
```
Решение на Java
```java=
public class Solution
{
public static int[] twoSum(int[] numbers, int target)
{
int n = numbers.length;
for(int i = 0; i < n - 1; i++)
for(int j = i + 1; j < n; j++)
if(numbers[i] + numbers[j] == target)
{
int[] res = new int[2];
res[0] = i;
res[1] = j;
return res;
}
return null;
}
}
```
Сложность О(n^2)
4. [The Modulo-3 Sequence](https://www.codewars.com/kata/589d33e4e0bbce5d6300061c) 6kyu
Consider a sequence where the first two numbers are 0 and 1 and the next number of the sequence is the sum of the previous 2 modulo 3. Write a function that finds the nth number of the sequence.
Рассмотрим последовательность, в которой первые два числа равны 0 и 1, а следующее число последовательности является суммой двух предыдущих по модулю 3. Напишите функцию, которая находит n-е число последовательности.
Решение на С++
```c++=
int sequence(int n)
{
int numbers[8] = {0, 1, 1, 2, 0, 2, 2, 1};
return numbers[(n-1)%8];
}
```
Решение на Java
```java=
public class Solution
{
public static int sequence(int n)
{
int[] numbers = new int[]{0, 1, 1, 2, 0, 2, 2, 1};
return numbers[(n-1)%8];
}
}
```
5. [Block sequence](https://www.codewars.com/kata/5e1ab1b9fe268c0033680e5f) 4kyu
Пока что решить не удалось.