Clasa a IX-a · high schoolCitește în română
Grade 9 algorithmsClasa a IX-a
The grade 9 part of the collection, chapter by chapter. Read the idea, run the code against the examples and track what you've learned.
- 87algorithms
- 8chapters
- 1grade
87 algorithms
Grade 9Clasa a IX-a
0%0%
Digits of a number
Cifrele unui număr · 15 algorithms
- Number of occurrences of digit kNumărul de apariții ale cifrei kWe go through the digits of n and count how many are equal to k. With do-while, for n = 0 and k = 0 the answer is correctly 1.
- Largest number formed from the digits of nCel mai mare număr format cu cifrele lui nWe count how many times each digit appears, in a frequency array with 10 positions (frecv[c] = how many times digit c appears). The largest number…
- Check digit (digital root)Cifra de controlThe check digit is obtained by repeatedly replacing the number with the sum of its digits until a single digit remains (for example 99999 -> 45 ->…
- Largest and smallest digitCifra maximă și cifra minimăWe start with the maximum at 0 (the smallest possible digit) and the minimum at 9 (the largest possible digit), then compare every digit with them.…
- Checking for distinct digitsVerificarea cifrelor distincteChecks whether all digits of n are different. We remember which digits we have already seen (vazut[c] becomes true on the first occurrence of c); if…
- Printing the digits in their order in the numberAfișarea cifrelor în ordinea din numărWith n % 10 the digits come out from right to left. To print them from left to right, we first compute p = the largest power of 10 not greater than…
- Doubling the odd digitsDublarea cifrelor impareEvery odd digit of n appears twice in the result. We build the result from right to left with rez = rez + digit * p; an odd digit is added twice, so…
- Removing the even digitsEliminarea cifrelor pareWe build a new number from the odd digits of n, keeping their order. The digits come from right to left, so every kept digit is placed in front of…
- Replacing one digit with anotherÎnlocuirea unei cifre cu altaReplaces every occurrence of digit x in n with digit y. We rebuild the number from right to left with rez = rez + digit * p, putting y in place of…
- Palindrome numberNumăr palindromA number is a palindrome if it reads the same from left to right and from right to left, i.e. it is equal to its reverse. We work on a copy, because…
- Number of digits of a numberNumărul de cifre ale unui numărCounts the digits of n by cutting off the last digit at every step (n / 10) until the number becomes 0. We use do-while so that the number 0 is…
- Reverse of a numberOglinditul unui numărBuilds the number made of the digits of n written in reverse order. At every step we take the last digit (n % 10), append it to the right of the…
- First digit of a numberPrima cifră a unui numărThe first (leftmost) digit is what remains after we cut off all the other digits: we divide by 10 while the number has at least two digits (n >= 10).
- Product of the digits of a numberProdusul cifrelor unui numărMultiplies the digits of n. The product starts from 1 (the identity element of multiplication), not from 0. With do-while, for n = 0 we correctly…
- Sum of the digits of a numberSuma cifrelor unui numărAdds up the digits of n. The last digit is obtained with n % 10, then removed with n / 10. We repeat until n becomes 0.
0%
Divisibility and prime numbers
Divizibilitate și numere prime · 17 algorithms
- GCD by repeated division (Euclid's algorithm)Cmmdc prin împărțiri repetate (algoritmul lui Euclid)The greatest common divisor does not change if we replace the pair (a, b) with (b, a % b). We repeat until b becomes 0; then the GCD is a. It also…
- GCD by repeated subtractionCmmdc prin scăderi repetateWe subtract the smaller number from the larger one until they become equal; the common value is the GCD. It only works for a, b > 0 (with a 0 the…
- Least common multipleCel mai mic multiplu comunWe use the relation gcd(a, b) * lcm(a, b) = a * b. We compute the GCD with Euclid's algorithm on copies of a and b, then lcm = a / gcd * b (we…
- Prime factorizationDescompunerea în factori primiWe try the factors d = 2, 3, 4, ... and divide n by d as many times as possible, counting how many times (the exponent). A composite d no longer…
- Prime divisors of a numberDivizorii primi ai unui numărThis is the prime factorization, printing only the factors, without exponents. Every factor found is removed completely from n.
- Proper divisors of a numberDivizorii proprii ai unui numărProper divisors are the divisors other than 1 and n. We use the same two passes as when printing all divisors, but start from d = 2, so 1 and its…
- Divisors of a numberDivizorii unui numărDivisors come in pairs: if d divides n, then n / d divides n too, and one of them is at most the square root of n. So it is enough to try d from 1…
- Euler's totient functionIndicatorul lui Eulerφ(n) is the number of values in 1..n that are coprime with n. If p1, p2, ... are the prime divisors of n, then φ(n) = n · (1 - 1/p1) · (1 - 1/p2) ·…
- Perfect numberNumăr perfectA number is perfect if it equals the sum of its divisors smaller than itself (6 = 1 + 2 + 3). We compute the sum of all divisors in O(√n) and…
- Number of divisorsNumărul divizorilorFor every d with d * d <= n that divides n we count two divisors, d and n / d, except when d * d == n, when the two coincide.
- Pairs of twin primesPerechi de numere prime gemeneTwo prime numbers are twins if their difference is 2 (for example 11 and 13). We print all pairs (p, p + 2) with p + 2 <= n, testing both numbers…
- Coprime numbersNumere prime între eleTwo numbers are coprime if their only common divisor is 1, i.e. gcd(a, b) = 1. The numbers themselves do not have to be prime: 15 and 28 are coprime.
- The first n prime numbersPrimele n numere primeWe take the candidates 2, 3, 4, ... one by one and test them with the primality test up to √x. We stop after printing n prime numbers.
- Simplifying a fractionSimplificarea unei fracțiiA fraction a / b becomes irreducible if we divide the numerator and the denominator by gcd(a, b). We compute the GCD on copies, to keep the original…
- Sum of divisorsSuma divizorilorWe add the divisors in pairs (d and n / d) for d * d <= n; when n is a perfect square, the root is added only once.
- Primality testTest de primalitateA number is prime if it has exactly two divisors: 1 and itself (so 0 and 1 are not prime). If n has a divisor d between 2 and n - 1, it also has one…
- Last digit of x to the power yUltima cifră a lui x la puterea yThe last digit of a product depends only on the last digits of the factors. The last digits of powers repeat with period 4 (for example for 3: 3, 9,…
0%
Number sequences read one at a time
Șiruri de numere citite pe rând · 13 algorithms
- Longest run of equal elementsCea mai lungă secvență de elemente egaleA run means elements on consecutive positions. lung is the length of the current run: it grows when the new number equals the previous one and goes…
- Largest Fibonacci term not greater than nCel mai mare termen Fibonacci cel mult egal cu nWe generate the terms of the Fibonacci sequence (1, 1, 2, 3, 5, ...) while the next term does not exceed n. The last term kept is the answer. We…
- The two largest valuesCele mai mari două valoriWe keep the largest value (max1) and the second one (max2). If the new number exceeds max1, the old max1 moves down to second place; otherwise, if…
- Reading a sequence terminated by 0Citirea unui șir terminat cu 0We do not know in advance how many numbers follow: we read up to the first 0, which only marks the end and is not part of the sequence. The program…
- GCD of several numbersCmmdc-ul mai multor numeregcd(a, b, c) = gcd(gcd(a, b), c). We keep in rez the GCD of the numbers read so far and combine it, with Euclid's algorithm, with every new number.…
- The n-th term of the Fibonacci sequenceAl n-lea termen al șirului lui FibonacciThe Fibonacci sequence starts with 1, 1 and every term is the sum of the two before it: 1, 1, 2, 3, 5, 8, ... We do not need an array: we keep only…
- Maximum and minimum of a sequenceMaximul și minimul unui șirn is read, then n integers. The maximum and the minimum start from the first number read (not from 0, because all numbers may be negative), then…
- Counting elements with a propertyNumărarea elementelor cu o proprietaten and n natural numbers are read. We count how many of them are even and how many have the last digit equal to the first. Each property has its own…
- Number of sign changesNumărul de schimbări de semnn non-zero numbers are read. A sign change happens between two consecutive terms with opposite signs, i.e. when their product is negative. We…
- Pairs of consecutive terms with a propertyPerechi de termeni consecutivi cu o proprietateWe count the pairs of adjacent terms that have the same parity. A sequence of n terms has n - 1 consecutive pairs; for every new term x, the pair is…
- Checking an arithmetic progressionVerificarea unei progresii aritmeticeA sequence is an arithmetic progression if the difference between two consecutive terms is always the same (the common difference). The difference…
- Checking a non-decreasing sequenceVerificarea unui șir crescătorThe sequence is non-decreasing if every number is at least equal to the one before it. We keep the previous number in the variable ant and compare…
- Sum and arithmetic meanSuma și media aritmeticăn and n integers are read; their sum and arithmetic mean are printed, with two decimals. For the mean we divide a real number by n (1.0 * suma / n);…
0%
Number bases
Baze de numerație · 6 algorithms
- Converting from base 10 to base bConversia din baza 10 în baza bWe repeatedly divide n by b; the remainders are the digits in base b, but they come from the last to the first. That is why every new digit is…
- Converting to base 10 using powers of the baseConversia în baza 10 cu puterile bazeiThe version for b <= 10, when the number can be read as an integer: its digits are extracted from the right with n % 10, and every digit is…
- Converting from base b to base 10Conversia din baza b în baza 10The number in base b is read as text (it may contain A..F), then Horner's scheme is applied: we go through the digits from left to right and do rez…
- Converting between any two basesConversia între două baze oarecareWe go through base 10: first we convert the number from base b1 to base 10 (Horner's scheme), then from base 10 to base b2 (repeated division). The…
- Number of 1 bits in binaryNumărul de biți 1 din scrierea în baza 2The base-2 digits are obtained just like the base-10 digits, except that we divide by 2: the last binary digit is n % 2. We count how many of them…
- Checking for a power of 2Verificarea unei puteri a lui 2A power of 2 has a single 1 bit in base 2 (for example 64 = 1000000). Subtracting 1 turns that bit into 0 and all the bits to its right into 1 (63 =…
0%
One-dimensional arrays (vectors)
Tablouri unidimensionale (vectori) · 11 algorithms
- Reading and printing an arrayCitirea și afișarea unui vectorAn array stores several values of the same type, accessed by index. We declare the array with a fixed maximum size and use positions 1..n. n and the…
- Removing the even elementsEliminarea elementelor pareInstead of deleting the even elements one by one (every deletion shifts the whole rest of the array), we make a single pass: k counts the elements…
- Inserting a value after every even elementInserarea unei valori după fiecare element parWe go through the array from the end to the beginning. When v[i] is even, we shift the elements after it one position to the right and put x at…
- Inserting an element at a positionInserarea unui element pe o pozițieTo put val at position poz, we make room: we shift the elements v[poz..n] one position to the right. Shifting starts from the end (from n down to…
- Reversing an arrayInversarea unui vectorWe swap the first element with the last, the second with the second to last, and so on: v[i] with v[n - i + 1]. We stop halfway (i <= n / 2); if we…
- The maximum and the positions where it appearsMaximul și pozițiile pe care apareUnlike a sequence read one value at a time, an array can be traversed several times: in the first pass we find the maximum, in the second we print…
- Circular shift to the rightPermutarea circulară la dreaptaEvery element moves one position to the right, and the last one goes to the first position. We save v[n], shift the rest from the end towards the…
- Circular shift to the leftPermutarea circulară la stângaEvery element moves one position to the left, and the first one goes to the last position. We save v[1] in a variable, shift the rest (v[i] = v[i +…
- Deleting the element at a positionȘtergerea elementului de pe o pozițieTo delete the element at position poz, we shift the elements after it one position to the left, from left to right (v[i] = v[i + 1]), then n…
- Sum of the elements on even and odd positionsSuma elementelor de pe pozițiile pare și impareMind the difference between the position (the index i) and the value (v[i]). Parity is checked here for the index: v[2], v[4], ... are on even…
- Checking a symmetric arrayVerificarea unui vector simetricAn array is symmetric (a palindrome) if v[i] = v[n - i + 1] for every i. We compare the pairs from both ends towards the middle and stop at the…
0%
Sorting and searching
Sortare și căutare · 10 algorithms
- Binary searchCăutarea binarăIt only works on an array sorted in increasing order. We compare x with the middle element of the range [st, dr]: if they are equal, we are done; if…
- Linear searchCăutarea secvențialăWe check the elements one by one, starting from the first, until we find the value x or reach the end of the array. It works on any array, sorted or…
- Merging two sorted arraysInterclasarea a doi vectori sortațiFrom two arrays sorted in increasing order we build a third, also sorted. We compare the current elements a[i] and b[j], copy the smaller one and…
- First position with a value greater than or equal to xPrima poziție cu valoare mai mare sau egală cu xThe binary search variant that does not stop at the first match: in an array sorted in increasing order, we look for the smallest position p with…
- Sorting with std::sortSortarea cu std::sortThe <algorithm> library has the sort function, which orders in O(n log n). It takes the start and the end of the range: for positions 1..n we write…
- Sorting by two criteriaSortarea după două criteriiWe order the numbers increasingly by their last digit, and numbers with the same last digit decreasingly by value. The sorting algorithm stays the…
- Insertion sortSortarea prin inserțieLike arranging playing cards in your hand: the first i - 1 elements are already sorted, and v[i] is inserted in its place among them. We save v[i]…
- Bubble sortSortarea prin metoda bulelorWe go through the array and swap any two neighbouring elements that are in the wrong order (v[i] > v[i + 1]). After every pass, the largest…
- Counting sortSortarea prin numărareWhen the values are small natural numbers (here 0..10000), we do not compare elements: we count how many times each value appears in a frequency…
- Selection sortSortarea prin selecțieFor every position i, from 1 to n - 1, we look for the minimum of v[i..n] and bring it to position i with a single swap. After step i, the first i…
0%
Frequency arrays, prefix sums and the Sieve of Eratosthenes
Frecvență, sume parțiale și ciurul lui Eratostene · 10 algorithms
- Common digits of two numbersCifrele comune a două numereIn two arrays of 10 positions we mark which digits appear in each number (aparA[c], aparB[c]). The common digits are the ones marked in both arrays;…
- Sieve of EratosthenesCiurul lui EratosteneFinds all prime numbers up to n. We start with all numbers unmarked; for every unmarked i (hence prime) we mark its multiples as not prime, starting…
- Majority elementElementul majoritarThe majority element appears more than n / 2 times. The voting algorithm (Boyer-Moore) keeps a candidate and a counter: an element equal to the…
- The missing number in a permutationNumărul lipsă dintr-o permutaren and n - 1 distinct numbers from the set {1, 2, ..., n} are given; exactly one is missing. The sum of all numbers from 1 to n is n · (n + 1) / 2…
- Subarray of length k with the maximum sumSecvența de lungime k cu suma maximăSliding window: we compute the sum of the first k elements, then slide the window one position to the right: we add the element that enters (v[i])…
- Maximum subarray sum (Kadane's algorithm)Secvența de sumă maximă (algoritmul lui Kadane)We go through the array and keep the sum of the current subarray, which ends at position i. If the sum so far has become negative, it no longer…
- Prefix sumsSume parțiales[i] = v[1] + v[2] + ... + v[i], with s[0] = 0, is computed in a single pass: s[i] = s[i - 1] + v[i]. Then the sum over any range [st, dr] is s[dr]…
- Distinct values and their frequenciesValorile distincte și frecvențele lorOnce the frequency array is built, the distinct values are the indices val with frecv[val] > 0. Going through them in increasing order, we print…
- Marking ranges with a difference arrayMarcarea intervalelor cu vectorul de diferențeWe have n positions, initially 0, and m operations 'add 1 to positions a..b'. Instead of walking every range, we only note its ends: d[a]++ (it…
- Frequency arrayVectorul de frecvențăFor small natural values (here 0..1000), frecv[x] stores how many times the value x has appeared. The value becomes an index, so every number read…
0%
Text files
Fișiere text · 5 algorithms
- Reading until the end of the fileCitirea până la sfârșitul fișieruluiThe file date.in contains integers, but we do not know how many. The expression fin >> x returns 'true' as long as reading succeeds and 'false' at…
- Counting the values in a fileNumărarea valorilor dintr-un fișierThe file date.in contains a natural number k on the first line, and on the following lines a sequence of natural numbers of unknown length. We read…
- Processing a file line by linePrelucrarea unui fișier pe liniigetline(fin, linie) reads a whole line, spaces included, up to '\n'. The loop while (getline(fin, linie)) stops at the end of the file. We count the…
- Formatted writing to a fileScrierea formatată într-un fișiern is read from date.in and the numbers from 1 to n are written to date.out, five per line. ofstream is used exactly like cout; a new line is written…
- Sum of the numbers on each lineSuma numerelor de pe fiecare linieEvery line of date.in contains a few integers, an unknown number of them. We read the line with getline, then 're-read' it as a stream of numbers…