text
stringlengths
2
104M
meta
dict
# Regex > Introduction > Matching Specific String # Match a specific string using regex. # # https://www.hackerrank.com/challenges/matching-specific-string/problem # https://www.hackerrank.com/contests/regular-expresso/challenges/matching-specific-string # challenge id: 13619 # Regex_Pattern = r'hackerrank' # Do not delete 'r'. # (skeliton_tail) ---------------------------------------------------------------------- import re Test_String = input() match = re.findall(Regex_Pattern, Test_String) print("Number of matches :", len(match))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Regex](https://www.hackerrank.com/domains/regex) Explore the power of regular expressions #### [Introduction](https://www.hackerrank.com/domains/regex/re-introduction) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Matching Specific String](https://www.hackerrank.com/challenges/matching-specific-string)|Match a specific string using regex.|[Python](matching-specific-string.py)|Easy [Matching Anything But a Newline](https://www.hackerrank.com/challenges/matching-anything-but-new-line)|Use [.] in the regex expression to match anything but a newline character.|[Python](matching-anything-but-new-line.py)|Easy [Matching Digits & Non-Digit Characters](https://www.hackerrank.com/challenges/matching-digits-non-digit-character)|Use the expression \d to match digits and \D to match non-digit characters.|[Python](matching-digits-non-digit-character.py)|Easy [Matching Whitespace & Non-Whitespace Character](https://www.hackerrank.com/challenges/matching-whitespace-non-whitespace-character)|Use \s to match whitespace and \S to match non whitespace characters in this challenge.|[Python](matching-whitespace-non-whitespace-character.py)|Easy [Matching Word & Non-Word Character](https://www.hackerrank.com/challenges/matching-word-non-word)|Use \w to match any word and \W to match any non-word character.|[Python](matching-word-non-word.py)|Easy [Matching Start & End](https://www.hackerrank.com/challenges/matching-start-end)|Use the ^ symbol to match the start of a string, and the $ symbol to match the end characters.|[Python](matching-start-end.py)|Easy
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# https://www.hackerrank.com/domains/mathematics add_subdirectory(fundamentals) add_subdirectory(number-theory) add_subdirectory(combinatorics) add_subdirectory(geometry) add_subdirectory(algebra) add_subdirectory(probability)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Mathematics](https://www.hackerrank.com/domains/mathematics) Without mathematics, there's nothing you can do. Everything around you is mathematics. Everything around you is numbers. #### [Fundamentals](https://www.hackerrank.com/domains/mathematics/fundamentals) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Find the Point](https://www.hackerrank.com/challenges/find-point)|Given two points P and Q, output the symmetric point of point P about Q.|[C++](fundamentals/find-point.cpp)|Easy [Maximum Draws](https://www.hackerrank.com/challenges/maximum-draws)|Count the minimum Draws|[Python](fundamentals/maximum-draws.py)|Easy [Handshake](https://www.hackerrank.com/challenges/handshake)|Count the number of Handshakes in a board meeting.|[Python](fundamentals/handshake.py)|Easy [Minimum Height Triangle](https://www.hackerrank.com/challenges/lowest-triangle)|Find the smallest height of a triangle preserving the given constraints.|[Python](fundamentals/lowest-triangle.py)|Easy [Army Game](https://www.hackerrank.com/challenges/game-with-cells)|Find the minimum number of supply packages Luke must drop to supply all of his army bases.|[Python](fundamentals/game-with-cells.py)|Easy [Leonardo's Prime Factors](https://www.hackerrank.com/challenges/leonardo-and-prime)|Find the maximum number of prime factors for any number in the inclusive range from 1 to n.|[Python](fundamentals/leonardo-and-prime.py)|Easy [Connecting Towns](https://www.hackerrank.com/challenges/connecting-towns)|Find the Number of ways to in which one can travel from one town to another.|[Python](fundamentals/connecting-towns.py)|Easy [Cutting Paper Squares](https://www.hackerrank.com/challenges/p1-paper-cutting)|Determine the number of cuts needed to cut a paper into $1 \times 1$ squares.|[Python](fundamentals/p1-paper-cutting.py)|Easy [Summing the N series ](https://www.hackerrank.com/challenges/summing-the-n-series)|Sum the N series.|[Python](fundamentals/summing-the-n-series.py)|Medium [Sherlock and Moving Tiles](https://www.hackerrank.com/challenges/sherlock-and-moving-tiles)|Help Sherlock in identifying the overlapping area.|[Python](fundamentals/sherlock-and-moving-tiles.py)|Easy [Best Divisor](https://www.hackerrank.com/challenges/best-divisor)|Find the best divisor of the number!|[Python](fundamentals/best-divisor.py)|Easy [Restaurant](https://www.hackerrank.com/challenges/restaurant)|Help Martha with her interview at Subway|[Python](fundamentals/restaurant.py)|Easy [Reverse Game](https://www.hackerrank.com/challenges/reverse-game)|Print the final position of the index.|[Python](fundamentals/reverse-game.py)|Easy [Strange Grid Again](https://www.hackerrank.com/challenges/strange-grid)|find the integer in c-th column in r-th row of the grid.|[Python](fundamentals/strange-grid.py)|Easy [Diwali Lights](https://www.hackerrank.com/challenges/diwali-lights)|Number of ways to light the room|[Python](fundamentals/diwali-lights.py)|Medium [Sherlock and Divisors](https://www.hackerrank.com/challenges/sherlock-and-divisors)|Help Sherlock in Counting Divisors.|[Python](fundamentals/sherlock-and-divisors.py)|Easy [Sherlock and Permutations](https://www.hackerrank.com/challenges/sherlock-and-permutations)|Help Sherlock in counting permutations.|[Python](fundamentals/sherlock-and-permutations.py)|Hard [Even Odd Query](https://www.hackerrank.com/challenges/even-odd-query)|Is the number odd or even?|[C++](fundamentals/even-odd-query.cpp) [Python](fundamentals/even-odd-query.py)|Hard [Special Multiple](https://www.hackerrank.com/challenges/special-multiple)|Can you find the least positive integer that is made of only 0s and 9s? - 30 Points|[C](fundamentals/special-multiple.c) [Python](fundamentals/special-multiple.py)|Medium [Matrix Tracing](https://www.hackerrank.com/challenges/matrix-tracing)|How many ways can you trace a given matrix? - 30 Points|[Python](fundamentals/matrix-tracing.py)|Hard [Die Hard 3](https://www.hackerrank.com/challenges/die-hard-3)|Help Bruce and Samuel save the city by solving their puzzle|[Python](fundamentals/die-hard-3.py)|Medium [Halloween party](https://www.hackerrank.com/challenges/halloween-party)|Help Alex give Silvia the maximum number of chocolates|[Python](fundamentals/halloween-party.py)|Easy [Filling Jars](https://www.hackerrank.com/challenges/filling-jars)|Perform the multiple queries on the list. And print average. - 20 Points|[Python](fundamentals/filling-jars.py)|Easy [Is Fibo](https://www.hackerrank.com/challenges/is-fibo)|Find out if a number is a Fibonacci Number or not.|[Python](fundamentals/is-fibo.py)|Medium [K Candy Store](https://www.hackerrank.com/challenges/k-candy-store)|In how many ways can you select K candies out of N different types of candies when each of the N candies are infinite in number?|[Python](fundamentals/k-candy-store.py)|Medium [Sumar and the Floating Rocks](https://www.hackerrank.com/challenges/harry-potter-and-the-floating-rocks)|Count the number of integral rocks between Harry and Hermoine|[Python](fundamentals/harry-potter-and-the-floating-rocks.py)|Easy [Russian Peasant Exponentiation](https://www.hackerrank.com/challenges/russian-peasant-exponentiation)|The only correct way to raise numbers in powers.|[Python](fundamentals/russian-peasant-exponentiation.py)|Easy [Bus Station](https://www.hackerrank.com/challenges/bus-station)|Find all suitable bus sizes|[Python](fundamentals/bus-station.py)|Medium [Most Distant](https://www.hackerrank.com/challenges/most-distant)|Measure the gap between the two most distant coordinates.|[Python](fundamentals/most-distant.py)|Easy [Jim and the Jokes](https://www.hackerrank.com/challenges/jim-and-the-jokes)|Jim is running out of jokes! Help him finding new jokes.|[Python](fundamentals/jim-and-the-jokes.py)|Medium [Possible Path](https://www.hackerrank.com/challenges/possible-path)|Help Adam in reaching at aa particular point.|[Python](fundamentals/possible-path.py)|Easy [Mutual Recurrences](https://www.hackerrank.com/challenges/mutual-recurrences)|Compute terms in a mutual recurrence.|[C++](fundamentals/mutual-recurrences.cpp) [Python](fundamentals/mutual-recurrences.py)|Medium #### [Number Theory](https://www.hackerrank.com/domains/mathematics/number-theory) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Constructing a Number](https://www.hackerrank.com/challenges/constructing-a-number)|Construct a number divisible by 3 from the given numbers by reordering their digits.|[Python](number-theory/constructing-a-number.py)|Easy [Closest Number](https://www.hackerrank.com/challenges/closest-number)|What is the closest number?|[Python](number-theory/closest-number.py)|Medium [Sherlock and GCD](https://www.hackerrank.com/challenges/sherlock-and-gcd)|Help Sherlock in finding the subset.|[Python](number-theory/sherlock-and-gcd.py)|Easy [Primitive Problem](https://www.hackerrank.com/challenges/primitive-problem)|Find the primitive roots of a prime number.|[Python](number-theory/primitive-problem.py)|Easy [Identify Smith Numbers](https://www.hackerrank.com/challenges/identify-smith-numbers)|Write a program to check whether a given integer is a Smith number.|[Python](number-theory/identify-smith-numbers.py)|Easy [Euler's Criterion](https://www.hackerrank.com/challenges/eulers-criterion)|Detect whether the number is a quadratic residue.|[Python](number-theory/eulers-criterion.py)|Easy [Twins](https://www.hackerrank.com/challenges/twins)|How many pairs of twins can you find?|[Python](number-theory/twins.py)|Medium [Fibonacci Finding (easy)](https://www.hackerrank.com/challenges/fibonacci-finding-easy)|Find some Fibonacci numbers!|[Python](number-theory/fibonacci-finding-easy.py)|Easy [Little Panda Power](https://www.hackerrank.com/challenges/littlepandapower)|Compute A^B mod X|[Python](number-theory/littlepandapower.py)|Hard [Mehta and his Laziness](https://www.hackerrank.com/challenges/mehta-and-his-laziness)|How will Mehta do these calculations?|[Python](number-theory/mehta-and-his-laziness.py)|Hard [Minimal Distance to Pi](https://www.hackerrank.com/challenges/minimal-distance-to-pi)|Given a range of denominators, find the common fraction that best approximates Pi.|[Python](number-theory/minimal-distance-to-pi.py)|Hard [Help Mike](https://www.hackerrank.com/challenges/help-mike)|Help Mike attend the NSA meeting|[Python](number-theory/help-mike.py)|Hard [Dancing in Pairs](https://www.hackerrank.com/challenges/dance-class)|Find out if they can dance in pairs?|[Python](number-theory/dance-class.py)|Hard [The Chosen One](https://www.hackerrank.com/challenges/the-chosen-one)|Given a list of integers, find and print an integer that is a divisor of all but one integer in the list.|[Python](number-theory/the-chosen-one.py)|Medium [Power of large numbers](https://www.hackerrank.com/challenges/power-of-large-numbers)|How much does Hackerland coach pay to get Cristiano Ronaldo to play for his team?|[Python](number-theory/power-of-large-numbers.py)|Medium [Salary Blues](https://www.hackerrank.com/challenges/salary-blues)|Help manager of HackerX company to normalize salaries.|[Python](number-theory/salary-blues.py)|Medium [Akhil and GF](https://www.hackerrank.com/challenges/akhil-and-gf)|Help Akhil in impressing his girlfriend|[Python](number-theory/akhil-and-gf.py)|Hard [Little Ashish's Huge Donation](https://www.hackerrank.com/challenges/little-chammys-huge-donation)|Help Ashish calculate donations.|[C++](number-theory/little-chammys-huge-donation.cpp)|Hard [Manasa and Factorials](https://www.hackerrank.com/challenges/manasa-and-factorials)|Think about number of zeros in k!|[Python](number-theory/manasa-and-factorials.py)|Hard [Number of zero-xor subsets](https://www.hackerrank.com/challenges/number-of-subsets)|How many subsets with zero xor are here?|[Python](number-theory/number-of-subsets.py)|Medium [Breaking Sticks](https://www.hackerrank.com/challenges/breaking-sticks)|Find the length of the longest sequence of moves.|[C++](number-theory/breaking-sticks.cpp)|Medium [Cheese and Random Toppings](https://www.hackerrank.com/challenges/cheese-and-random-toppings)|How many ways are there to choose exactly R toppings from N toppings?|[Python](number-theory/cheese-and-random-toppings.py)|Easy [Easy GCD](https://www.hackerrank.com/challenges/easy-gcd-1)|Find the maximum number less than K such that GCD of all numbers is still more than one!|[Python](number-theory/easy-gcd-1.py)|Medium [Satisfactory Pairs](https://www.hackerrank.com/challenges/pairs-again)|How many pairs of integers give a solution?|[C++](number-theory/pairs-again.cpp)|Hard [Manasa loves Maths](https://www.hackerrank.com/challenges/manasa-loves-maths)|Find out if any permutation of the given number is divisible by 8.|[Python](number-theory/manasa-loves-maths.py)|Medium [Largest Non-Coprime Submatrix](https://www.hackerrank.com/challenges/largest-coprime-submatrix)|Given a matrix find the largest coprime submatrix.|[C++](number-theory/largest-coprime-submatrix.cpp)|Hard [John and GCD list](https://www.hackerrank.com/challenges/john-and-gcd-list)|Help John in making a list from GCD list|[Python](number-theory/john-and-gcd-list.py)|Easy [Divisor Exploration II](https://www.hackerrank.com/challenges/divisor-exploration-2)|Find the product of a sequence and then calculate the summation of its divisors.|[Python](number-theory/divisor-exploration-2.py)|Hard [Strange numbers](https://www.hackerrank.com/challenges/strange-numbers)|How many strange numbers belong to interval [L, R]?|[Python](number-theory/strange-numbers.py)|Hard [Easy math](https://www.hackerrank.com/challenges/easy-math)|Help Johnny in figuring out the value of Y|[Python](number-theory/easy-math.py)|Medium [Equations](https://www.hackerrank.com/challenges/equations)|Find the number of positive integral solutions for an equation.|[Python](number-theory/equations.py)|Medium [Binomial Coefficients](https://www.hackerrank.com/challenges/binomial-coefficients)|Calculate how many binomial coefficients of n become 0 after modulo by P.|[Python](number-theory/binomial-coefficients.py)|Medium [Lucy and Flowers](https://www.hackerrank.com/challenges/lucy-and-flowers)|Help Lucy's father with a computation involving flowers|[C++](number-theory/lucy-and-flowers.cpp)|Medium [Divisor Exploration 3](https://www.hackerrank.com/challenges/divisor-exploration-3)|Find the value given at the root of a tree constructing by the given rules.|[C++](number-theory/divisor-exploration-3.cpp) [Python](number-theory/divisor-exploration-3.py)|Hard [Superpowers of 2](https://www.hackerrank.com/challenges/superpowers)|Just another numbers problem...|[Python](number-theory/superpowers.py)|Advanced [Sherlock Puzzle](https://www.hackerrank.com/challenges/sherlock-puzzle)|Help Sherlock get close to his Arch Nemesis, Jim Moriarty.|[Python](number-theory/sherlock-puzzle.py)|Hard [Divisibility of Power](https://www.hackerrank.com/challenges/divisibility-of-power)|Divisibility Test.|[Python](number-theory/divisibility-of-power.py)|Medium [Devu Vs Police](https://www.hackerrank.com/challenges/devu-police)|Help Devu escape from police|[Python](number-theory/devu-police.py)|Hard [Long Permutation](https://www.hackerrank.com/challenges/long-permutation)|Determine the n^th element of an infinite permutation!|[Python](number-theory/long-permutation.py)|Hard [Megaprime Numbers](https://www.hackerrank.com/challenges/megaprime-numbers)|Count the number of primes in a given range that consist only of prime digits.|[Python](number-theory/megaprime-numbers.py)|Medium [Divisor Exploration](https://www.hackerrank.com/challenges/divisor-exploration)|Find and print the number of divisors for each dataset.|[Python](number-theory/divisor-exploration.py)|Hard [Prime Sum](https://www.hackerrank.com/challenges/prime-sum)|Represent a number as sum of primes.|[Python](number-theory/prime-sum.py)|Medium [nCr](https://www.hackerrank.com/challenges/ncr)|Given n and r, in how many ways can r items be chosen from n items?|[Python](number-theory/ncr.py)|Expert [Fibonacci GCD](https://www.hackerrank.com/challenges/fibonacci-gcd)|Find gcd for n fibonacci numbers.|[Python](number-theory/fibonacci-gcd.py)|Hard #### [Combinatorics](https://www.hackerrank.com/domains/mathematics/combinatorics) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [nCr table](https://www.hackerrank.com/challenges/ncr-table)|Help Jim calculating nCr values|[C++](combinatorics/ncr-table.cpp) [Python](combinatorics/ncr-table.py)|Medium [Coinage](https://www.hackerrank.com/challenges/coinage)|Find the number of ways to pay a given amount, given a set of coins with prescribed denominations.|[Python](combinatorics/coinage.py)|Medium [Building a List](https://www.hackerrank.com/challenges/building-a-list)|Generate all possible combinations of a string|[Python](combinatorics/building-a-list.py)|Medium [Merge List](https://www.hackerrank.com/challenges/merge-list)|Help Shashank in merging two list.|[Python](combinatorics/merge-list.py)|Medium [A Chocolate Fiesta](https://www.hackerrank.com/challenges/a-chocolate-fiesta)|Find the number of even subsets in the given set of numbers.|[Python](combinatorics/a-chocolate-fiesta.py)|Easy [Sherlock and Pairs](https://www.hackerrank.com/challenges/sherlock-and-pairs)|Count the number of pairs that satisfy a given constraint.|[Python](combinatorics/sherlock-and-pairs.py)|Medium [Picking Cards](https://www.hackerrank.com/challenges/picking-cards)|How many ways can you pick up all the cards from a table?|[Python](combinatorics/picking-cards.py)|Easy #### [Algebra](https://www.hackerrank.com/domains/mathematics/algebra) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Combo Meal](https://www.hackerrank.com/challenges/combo-meal)|Find the profit that a fast-food chain earns at each purchase.|[Python](algebra/combo-meal.py)|Easy [Stepping Stones Game](https://www.hackerrank.com/challenges/stepping-stones-game)|Can you tell Bob, if he should play Stepping Stones or not ?|[Python](algebra/stepping-stones-game.py)|Medium [Shashank and List](https://www.hackerrank.com/challenges/shashank-and-list)|Help Shashank in Huge calculations.|[Python](algebra/shashank-and-list.py)|Medium [Triangle Numbers](https://www.hackerrank.com/challenges/triangle-numbers)|Given a triangle numbers where each number is equal to the sum of the three top numbers, find the first even number in a row.|[Python](algebra/triangle-numbers.py)|Medium [Little Gaurav and Sequence](https://www.hackerrank.com/challenges/little-gaurav-and-sequence)|Help Gaurav in calculating last digit of a sequence.|[Python](algebra/little-gaurav-and-sequence.py)|Medium [Easy sum](https://www.hackerrank.com/challenges/easy-sum)|Find the mod sum|[Python](algebra/easy-sum.py)|Hard [Difference and Product](https://www.hackerrank.com/challenges/difference-and-product)|Answer a question about Difference and Product|[Python](algebra/difference-and-product.py)|Easy [Pythagorean Triple](https://www.hackerrank.com/challenges/pythagorean-triple)|Find the Pythagorean triple for the given side a.|[Python](algebra/pythagorean-triple.py)|Easy [Number Groups](https://www.hackerrank.com/challenges/number-groups)|Find the sum of consecutive odd number groups.|[Python](algebra/number-groups.py)|Easy [Tell the Average](https://www.hackerrank.com/challenges/tell-the-average)|Tell me average of all list value.|[Python](algebra/tell-the-average.py)|Medium [Wet Shark and 42](https://www.hackerrank.com/challenges/wet-shark-and-42)|Help Wet Shark escape the gods of 42.|[Python](algebra/wet-shark-and-42.py)|Easy [Sherlock and Square](https://www.hackerrank.com/challenges/sherlock-and-square)|Help Sherlock in finding the total side lengths of squares.|[Python](algebra/sherlock-and-square.py)|Hard [Manasa and Sub-sequences ](https://www.hackerrank.com/challenges/manasa-and-sub-sequences)|Help Manasa in getting candies|[Python](algebra/manasa-and-sub-sequences.py)|Medium [Simple One](https://www.hackerrank.com/challenges/simple-one)|Calculate the tan function of a given equation.|[Python](algebra/simple-one.py)|Easy #### [Geometry](https://www.hackerrank.com/domains/mathematics/geometry) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Points On a Line](https://www.hackerrank.com/challenges/points-on-a-line)|Given a set of coordinates, determine if they fall in an horizontal or vertical line.|[Python](geometry/points-on-a-line.py)|Easy [Rectangular Game](https://www.hackerrank.com/challenges/rectangular-game)|What's the largest number in the rectangular grid?|[Python](geometry/rectangular-game.py)|Easy [Sherlock and Counting](https://www.hackerrank.com/challenges/sherlock-and-counting)|Help Sherlock count numbers satisfying an inequality.|[Python](geometry/sherlock-and-counting.py)|Easy [Sherlock and Planes](https://www.hackerrank.com/challenges/sherlock-and-planes)|Help Sherlock with points on planes.|[Python](geometry/sherlock-and-planes.py)|Easy [Circle City](https://www.hackerrank.com/challenges/circle-city)|Determine whether Roy's city can be saved or not.|[Python](geometry/circle-city.py)|Medium [Xrange's Pancakes](https://www.hackerrank.com/challenges/xrange-and-pizza)|Determine who needs to be added to the end of the line to restore the pancake to its initial orientation.|[Python](geometry/xrange-and-pizza.py)|Easy [Baby Step, Giant Step](https://www.hackerrank.com/challenges/baby-step-giant-step)|Find the minimum number of steps needed to get to point $(d, 0)$.|[Python](geometry/baby-step-giant-step.py)|Medium [Points on a Rectangle](https://www.hackerrank.com/challenges/points-on-rectangle)|Determine if a set of points coincides with the edges of a non-degenerate rectangle.|[Python](geometry/points-on-rectangle.py)|Easy [A Circle and a Square](https://www.hackerrank.com/challenges/a-circle-and-a-square)|Draw a circle and a square at specific coordinates within a raster image.|[C++](geometry/a-circle-and-a-square.cpp)|Medium #### [Probability](https://www.hackerrank.com/domains/mathematics/probability) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Random number generator](https://www.hackerrank.com/challenges/random-number-generator)|what's the probability that x + y is less than C?|[Python](probability/random-number-generator.py)|Easy [Sherlock and Probability](https://www.hackerrank.com/challenges/sherlock-and-probability)|Help Sherlock in finding the probability.|[Python](probability/sherlock-and-probability.py)|Hard [Day 4: Normal Distribution #1](https://www.hackerrank.com/challenges/normal-distribution-1)|Problems based on basic statistical distributions.|[Python](probability/normal-distribution-1.py)|Medium [Day 4: Normal Distribution #2](https://www.hackerrank.com/challenges/normal-distribution-2)|Problems based on basic statistical distributions.|[Python](probability/normal-distribution-2.py)|Medium [Normal Distribution #3](https://www.hackerrank.com/challenges/normal-distribution-3)|Problems based on basic statistical distributions.|[Python](probability/normal-distribution-3.py)|Hard [B'day Gift](https://www.hackerrank.com/challenges/bday-gift)|Whats the price Isaac has to pay for HackerPhone|[Python](probability/bday-gift.py)|Easy [Extremely Dangerous Virus](https://www.hackerrank.com/challenges/extremely-dangerous-virus)|Estimate how large the virus will grow.|[Python](probability/extremely-dangerous-virus.py)|Medium [Binomial Distribution #1](https://www.hackerrank.com/challenges/binomial-distribution-1)|Problems based on basic statistical distributions.|[Python](probability/binomial-distribution-1.py)|Medium [Binomial Distribution #2](https://www.hackerrank.com/challenges/binomial-distribution-2)|Problems based on basic statistical distributions.|[Python](probability/binomial-distribution-2.py)|Hard [Binomial Distribution #3](https://www.hackerrank.com/challenges/binomial-distribution-3)|Problems based on basic statistical distributions.|[Python](probability/binomial-distribution-3.py)|Hard #### [Linear Algebra Foundations](https://www.hackerrank.com/domains/mathematics/linear-algebra-foundations) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Linear Algebra Foundations #1 - Matrix Addition](https://www.hackerrank.com/challenges/linear-algebra-foundations-1)|The basics of linear algebra and matrices as required in Machine Learning.|[text](linear-algebra-foundations/linear-algebra-foundations-1.txt)|Easy [Linear Algebra Foundations #2 - Matrix Subtraction](https://www.hackerrank.com/challenges/linear-algebra-foundations-1-matrix-subtraction)|The basics of linear algebra and matrices as required in Machine Learning.|[text](linear-algebra-foundations/linear-algebra-foundations-1-matrix-subtraction.txt)|Easy [Linear Algebra Foundations #3- Matrix Multiplication](https://www.hackerrank.com/challenges/linear-algebra-foundations-3-matrix-multiplication)|Matrix Multiplication of 2x2 Matrices|[Python](linear-algebra-foundations/linear-algebra-foundations-3-matrix-multiplication.py) [text](linear-algebra-foundations/linear-algebra-foundations-3-matrix-multiplication.txt)|Easy [Linear Algebra Foundations #4- Matrix Multiplication](https://www.hackerrank.com/challenges/linear-algebra-foundations-4-matrix-multiplication)|Matrix Multiplication of 2x2 Matrices|[Python](linear-algebra-foundations/linear-algebra-foundations-4-matrix-multiplication.py)|Easy [Linear Algebra Foundations #5 - The 100th Power of a Matrix](https://www.hackerrank.com/challenges/linear-algebra-foundations-5-the-100th-power-of-a-matrix)|Compute the 100<sup>the</sup> power of a given matrix.|[Python](linear-algebra-foundations/linear-algebra-foundations-5-the-100th-power-of-a-matrix.py)|Medium [Linear Algebra Foundations #6 - An Equation involving Matrices](https://www.hackerrank.com/challenges/linear-algebra-foundations-6-the-nsupthsup-power-of-a-matrix)|Solve an equation involving matrices.|[text](linear-algebra-foundations/linear-algebra-foundations-6-the-nsupthsup-power-of-a-matrix.txt)|Medium [Linear Algebra Foundations #7 - The 1000th Power of a Matrix](https://www.hackerrank.com/challenges/linear-algebra-foundations-7-the-1000th-power-of-a-matrix)|Compute the 1000th power of the given matrix.|[Python](linear-algebra-foundations/linear-algebra-foundations-7-the-1000th-power-of-a-matrix.py) [text](linear-algebra-foundations/linear-algebra-foundations-7-the-1000th-power-of-a-matrix.txt)|Hard [Linear Algebra Foundations #8 - Systems of Equations](https://www.hackerrank.com/challenges/linear-algebra-fundamentals-8-systems-of-equations)|A system of equations with no solutions.|[Python](linear-algebra-foundations/linear-algebra-fundamentals-8-systems-of-equations.py)|Hard [Linear Algebra Foundations #9 - Eigenvalues](https://www.hackerrank.com/challenges/linear-algebra-fundamentals-9-eigenvalues)|Compute the Eigenvalues of the following 2x2 matrix.|[text](linear-algebra-foundations/linear-algebra-fundamentals-9-eigenvalues.txt)|Hard [Linear Algebra Foundations #10 - Eigenvectors](https://www.hackerrank.com/challenges/linear-algebra-fundamentals-10-eigenvectors)|Compute the EigenVectors of the following 2x2 matrix.|[Python](linear-algebra-foundations/linear-algebra-fundamentals-10-eigenvectors.py)|Medium [Determinant of the matrix #1](https://www.hackerrank.com/challenges/determinant-of-the-matrix-1)|Basic problems related to determinants.|[Python](linear-algebra-foundations/determinant-of-the-matrix-1.py)|Medium [Determinant of the matrix #2](https://www.hackerrank.com/challenges/determinant-of-the-matrix-2)|Basic problems related to determinants.|[text](linear-algebra-foundations/determinant-of-the-matrix-2.txt)|Hard [Determinant of the matrix #3](https://www.hackerrank.com/challenges/determinant-of-the-matrix-3)|Basic problems related to determinants.|[text](linear-algebra-foundations/determinant-of-the-matrix-3.txt)|Medium [Eigenvalue of a Matrix I](https://www.hackerrank.com/challenges/eigenvalue-of-matrix-1)|Basic problems related to eigenvalues.|[Python](linear-algebra-foundations/eigenvalue-of-matrix-1.py)|Hard [Eigenvalue of matrix #2](https://www.hackerrank.com/challenges/eigenvalue-of-matrix-2)|Basic problems related to eigenvalues.|[Python](linear-algebra-foundations/eigenvalue-of-matrix-2.py)|Hard [Eigenvalue of matrix #3](https://www.hackerrank.com/challenges/eigenvalues-of-matrix-3)|Basic problems related to eigenvalues.|[Python](linear-algebra-foundations/eigenvalues-of-matrix-3.py)|Hard [Eigenvalue of matrix #4](https://www.hackerrank.com/challenges/eigenvalues-of-matrix-4)|Basic problems related to eigenvalues.|[Python](linear-algebra-foundations/eigenvalues-of-matrix-4.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Mathematics > Geometry > A Circle and a Square // Draw a circle and a square at specific coordinates within a raster image. // // https://www.hackerrank.com/challenges/a-circle-and-a-square/problem // https://www.hackerrank.com/contests/w29/challenges/a-circle-and-a-square // challenge id: 30440 // #include <bits/stdc++.h> using namespace std; struct point { int x; int y; }; int sign(const point& p1, const point& p2, const point& p3) { return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y); } bool pntriangle(const point& pt, const point& v1, const point& v2, const point& v3) { bool b1, b2, b3; b1 = sign(pt, v1, v2) < 0; b2 = sign(pt, v2, v3) < 0; b3 = sign(pt, v3, v1) < 0; return ((b1 == b2) && (b2 == b3)); } bool pisquare(const int x[4], const int y[4], int testx, int testy) { point pt { testx, testy}; point v1 { x[0], y[0] }, v2 { x[1], y[1] }, v3 { x[2], y[2] }, v4 { x[3], y[3] }; return pntriangle(pt, v1, v2, v3) || pntriangle(pt, v1, v3, v4); } int main() { int w, h; int xc, yc, r; int xs[4], ys[4]; int x, y; cin >> w >> h; cin >> xc >> yc >> r; cin >> xs[0] >> ys[0] >> xs[2] >> ys[2]; // l'astuce consiste à doubler les coordonnées du carré pour gérer les cas où // les deux autres sommets ont des coordonnées en 0.5 xs[0] *= 2; ys[0] *= 2; xs[2] *= 2; ys[2] *= 2; // calcul des deux autres sommets du carré x = (xs[0] + xs[2]) / 2; y = (ys[0] + ys[2]) / 2; xs[1] = x + (y - ys[0]); ys[1] = y - (x - xs[0]); xs[3] = x - (y - ys[0]); ys[3] = y + (x - xs[0]); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { char c = '.'; // est-ce que (x, y) est dans le cercle ? if ((x - xc) * (x - xc) + (y - yc) * (y - yc) <= r * r) { c = '#'; } // est-ce que le point est dans le carré ? else if (pisquare(xs, ys, x * 2, y * 2)) { c = '#'; } cout << c; } cout << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Xrange's Pancakes # Determine who needs to be added to the end of the line to restore the pancake to its initial orientation. # # https://www.hackerrank.com/challenges/xrange-and-pizza/problem # https://www.hackerrank.com/contests/infinitum16/challenges/xrange-and-pizza # challenge id: 12799 # n, m = map(int, input().split()) a = 0 # position du pancake flip = False # est-ce qu'on l'a retourné? for _ in range(m): op, k = map(int, input().split()) if op == 1: a = (a + k) % n # rotation de k else: a = (n - a + k) % n # flip et rotation de k flip = not flip if flip: print(2, a) else: print(1, (n - a) % n)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Baby Step, Giant Step # Find the minimum number of steps needed to get to point $(d, 0)$. # # https://www.hackerrank.com/challenges/baby-step-giant-step/problem # for _ in range(int(input())): a, b, d = map(int, input().split()) if d == 0: # rien à faire print(0) elif d == a or d == b: # en un coup, on y est print(1) elif d < b: # un triangle isocèle print(2) else: if d % b == 0: # on se déplace uniquement sur (x) print(d // b) else: # on se déplace sur (x) et un triangle isocèle print(d // b + 1)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Sherlock and Planes # Help Sherlock with points on planes. # # https://www.hackerrank.com/challenges/sherlock-and-planes/problem # https://www.hackerrank.com/contests/infinitum-may14/challenges/sherlock-and-planes # # je n'ai pas tout à faire le droit à numpy mais je me l'octroie !!! import sys sys.path += ['/var/ml/python3/lib/python3.5/site-packages'] import numpy for _ in range(int(input())): # lit les quatre points A,B,C,D A = numpy.array(input().split(), numpy.int) B = numpy.array(input().split(), numpy.int) C = numpy.array(input().split(), numpy.int) D = numpy.array(input().split(), numpy.int) v = numpy.cross(B - A, C - A) w = numpy.dot(D - A, v) if w == 0: print("YES") else: print("NO")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Sherlock and Counting # Help Sherlock count numbers satisfying an inequality. # # https://www.hackerrank.com/challenges/sherlock-and-counting/problem # from math import sqrt, floor, ceil for _ in range(int(input())): n, k = map(int, input().split()) # résoud x*(n-x)=n*k # les solutions seront les entiers entre [0, n] # qui ne sont pas dans la parabole (sommet vers le haut), i.e dans [r1, r2] # __ # r1 / \ r2 # +__________/____\________+___ # 0 / \ n # / \ D = n * n - 4 * k * n if D <= 0: print(n - 1) else: r1 = (n - sqrt(D)) / 2 r2 = (n + sqrt(D)) / 2 print(floor(r1) + (n - ceil(r2)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# https://www.hackerrank.com/domains/mathematics/geometry add_hackerrank_py(points-on-a-line.py) add_hackerrank_py(baby-step-giant-step.py) add_hackerrank_py(rectangular-game.py) add_hackerrank_py(sherlock-and-counting.py) add_hackerrank_py(points-on-rectangle.py) add_hackerrank_py(sherlock-and-planes.py) add_hackerrank_py(circle-city.py) add_hackerrank_py(xrange-and-pizza.py) add_hackerrank(a-circle-and-a-square a-circle-and-a-square.cpp)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Points On a Line # Given a set of coordinates, determine if they fall in an horizontal or vertical line. # # https://www.hackerrank.com/challenges/points-on-a-line/problem # x0, y0 = 0, 0 same_x, same_y = True, True n = int(input()) for i in range(n): x, y = map(int, input().split()) if i == 0: x0, y0 = x, y else: same_x = same_x and x == x0 same_y = same_y and y == y0 print("YES" if same_x or same_y else "NO")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Rectangular Game # What's the largest number in the rectangular grid? # # https://www.hackerrank.com/challenges/rectangular-game/problem # # sans forcer, la réponse est clairement min(x) * min(y) n = int(input()) mx, my = map(int, input().split()) for _ in range(n - 1): x, y = map(int, input().split()) mx = min(x, mx) my = min(y, my) print(mx * my)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Circle City # Determine whether Roy's city can be saved or not. # # https://www.hackerrank.com/challenges/circle-city/problem # https://www.hackerrank.com/contests/101aug14/challenges/circle-city # # https://fr.wikipedia.org/wiki/Théorème_des_deux_carrés_de_Fermat#Le_cas_général # le nombre de décompositions d'un entier n en somme de deux carrés est égal # à 4*(d1 - d3) où d1 (resp. d3) = nombre de diviseurs congrus à 1 mod 4 (resp. 3) import sys def diviseurs(n): div = [1] i = 2 while i * i <= n: q, r = divmod(n, i) if r == 0: div.append(i) if i != q: div.append(q) i += 1 if n != 1: div.append(n) return div for _ in range(int(input())): rr, k = map(int, input().split()) d = diviseurs(rr) d1 = sum(1 for i in d if i % 4 == 1) d3 = sum(1 for i in d if i % 4 == 3) r2 = 4 * (d1 - d3) print("n={} div={} d1={} d3={} r2={}".format(rr, d, d1, d3, r2), file=sys.stderr) if k >= r2: print("possible") else: print("impossible")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Geometry > Points on a Rectangle # Determine if a set of points coincides with the edges of a non-degenerate rectangle. # # https://www.hackerrank.com/challenges/points-on-rectangle/problem # https://www.hackerrank.com/contests/101hack42/challenges/points-on-rectangle # # le rectangle a ses côtés parralèles aux axes, ça simplifie grandement les choses ! # ces côtés sont définis par les valeurs min et max de x,y # le rectangle a ses côtés parralèles aux axes, ça simplifie grandement les choses ! # ces côtés sont définis par les valeurs min et max de x,y for _ in range(int(input())): n = int(input()) x, y = [0] * n, [0] * n for i in range(n): x[i], y[i] = map(int, input().split()) x0, y0 = min(x), min(y) x1, y1 = max(x), max(y) # il faut que tous les points soient sur x0, y0, x1 ou y1 ok = all((x[i] == x0) or (y[i] == y0) or (x[i] == x1) or (y[i] == y1) for i in range(n)) print(["NO", "YES"][ok])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Mathematics](https://www.hackerrank.com/domains/mathematics) Without mathematics, there's nothing you can do. Everything around you is mathematics. Everything around you is numbers. #### [Geometry](https://www.hackerrank.com/domains/mathematics/geometry) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Points On a Line](https://www.hackerrank.com/challenges/points-on-a-line)|Given a set of coordinates, determine if they fall in an horizontal or vertical line.|[Python](points-on-a-line.py)|Easy [Rectangular Game](https://www.hackerrank.com/challenges/rectangular-game)|What's the largest number in the rectangular grid?|[Python](rectangular-game.py)|Easy [Sherlock and Counting](https://www.hackerrank.com/challenges/sherlock-and-counting)|Help Sherlock count numbers satisfying an inequality.|[Python](sherlock-and-counting.py)|Easy [Sherlock and Planes](https://www.hackerrank.com/challenges/sherlock-and-planes)|Help Sherlock with points on planes.|[Python](sherlock-and-planes.py)|Easy [Circle City](https://www.hackerrank.com/challenges/circle-city)|Determine whether Roy's city can be saved or not.|[Python](circle-city.py)|Medium [Xrange's Pancakes](https://www.hackerrank.com/challenges/xrange-and-pizza)|Determine who needs to be added to the end of the line to restore the pancake to its initial orientation.|[Python](xrange-and-pizza.py)|Easy [Baby Step, Giant Step](https://www.hackerrank.com/challenges/baby-step-giant-step)|Find the minimum number of steps needed to get to point $(d, 0)$.|[Python](baby-step-giant-step.py)|Medium [Points on a Rectangle](https://www.hackerrank.com/challenges/points-on-rectangle)|Determine if a set of points coincides with the edges of a non-degenerate rectangle.|[Python](points-on-rectangle.py)|Easy [A Circle and a Square](https://www.hackerrank.com/challenges/a-circle-and-a-square)|Draw a circle and a square at specific coordinates within a raster image.|[C++](a-circle-and-a-square.cpp)|Medium
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Eigenvalue of matrix #4 # Basic problems related to eigenvalues. # # https://www.hackerrank.com/challenges/eigenvalues-of-matrix-4/problem # import numpy as np A = np.matrix([[ 2, -1], [-1, 2]]) I = np.identity(np.linalg.matrix_rank(A)) print(np.linalg.eigvals(np.linalg.inv(A))) print(np.linalg.eigvals(A - 4 * I))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #4- Matrix Multiplication # Matrix Multiplication of 2x2 Matrices # # https://www.hackerrank.com/challenges/linear-algebra-foundations-4-matrix-multiplication/problem # import numpy as np a = np.matrix([[1,2,3], [2,3,4], [1,1,1]]) b = np.matrix([[4,5,6], [7,8,9], [4,5,7]]) print(a * b) """ réponse: 30 36 45 45 54 67 15 18 22 """
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Eigenvalue of matrix #3 # Basic problems related to eigenvalues. # # https://www.hackerrank.com/challenges/eigenvalues-of-matrix-3/problem # import numpy as np a = np.matrix([[2, -1], [-1, 2]]) print(np.linalg.eigvalsh(a)) print(np.linalg.eigvalsh(a * a)) """ réponse: 1 3 1 9 """
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #1 - Matrix Addition # The basics of linear algebra and matrices as required in Machine Learning. # # https://www.hackerrank.com/challenges/linear-algebra-foundations-1/problem # 5 7 9 9 11 13 5 6 8
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #6 - An Equation involving Matrices # Solve an equation involving matrices. # # https://www.hackerrank.com/challenges/linear-algebra-foundations-6-the-nsupthsup-power-of-a-matrix/problem # réponse: -2 1 # A^2 = [[ 1 2 0] # [ 0 1 0] # [ 0 0 1]]
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Eigenvalue of a Matrix I # Basic problems related to eigenvalues. # # https://www.hackerrank.com/challenges/eigenvalue-of-matrix-1/problem # import numpy as np M = np.matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]]) print(np.linalg.eigvals(M)) I = np.identity(np.linalg.matrix_rank(M)) for λ in np.linalg.eigvals(M): print(np.linalg.det(M - λ * I))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Determinant of the matrix #1 # Basic problems related to determinants. # # https://www.hackerrank.com/challenges/determinant-of-the-matrix-1/problem # import numpy as np M = np.matrix([[ 3, 0, 0, -2, 4], [ 0, 2, 0, 0, 0], [ 0, -1, 0, 5, -3], [ -4, 0, 1, 0, 6], [ 0, -1, 0, 3, 2]]) M = np.matrix([[ a, b, c], [ d, e, f], [ g, h, h]]) print(round(np.linalg.det(M))) # réponse: -114
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Determinant of the matrix #2 # Basic problems related to determinants. # # https://www.hackerrank.com/challenges/determinant-of-the-matrix-2/problem # # det(A) = 5 # det(2A) = 5 * 2^dim(A) = 5 * 2^3 = 40 # det(transpose(A)) = det(A) = 5 # réponse: 5 40
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #7 - The 1000th Power of a Matrix # Compute the 1000th power of the given matrix. # # https://www.hackerrank.com/challenges/linear-algebra-foundations-7-the-1000th-power-of-a-matrix/problem # SOLUTION "EASY": avec numpy In [1]: import numpy as np In [2]: A = np.matrix([[-2, -9], [1, 4]]) In [3]: A ** 1000 Out[3]: matrix([[-2999, -9000], [ 1000, 3001]]) Réponse: -2999 -9000 1000 3001
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #3- Matrix Multiplication # Matrix Multiplication of 2x2 Matrices # # https://www.hackerrank.com/challenges/linear-algebra-foundations-3-matrix-multiplication/problem # import numpy as np a = np.matrix([[1, 2], [2, 3]]) b = np.matrix([[4, 5], [7, 8]]) p = a * b print(p)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #9 - Eigenvalues # Compute the Eigenvalues of the following 2x2 matrix. # # https://www.hackerrank.com/challenges/linear-algebra-fundamentals-9-eigenvalues/problem # # http://mathworld.wolfram.com/Eigenvalue.html Définition générale det(A-λI) = 0 Solution générale pour dim=2 λ = 1/2 [ (a11 + a22] ± sqrt(4 * a12 * a21 + (a11 - a22)^2) ] Solution avec numpy print(np.linalg.eigvals(np.matrix([[0, 1],[ -2, -3]]))) Solution calulée: A = [0 1] [-2 -3] λ = 1/2 * (-3 ± sqrt(-8+3^2)) ⟹ λ₁ = -4/2 = -2 ⟹ λ₂ = -2/2 = -1 Réponse: -2 -1
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #2 - Matrix Subtraction # The basics of linear algebra and matrices as required in Machine Learning. # # https://www.hackerrank.com/challenges/linear-algebra-foundations-1-matrix-subtraction/problem # -3 -3 -3 -5 -5 -5 -3 -4 1
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# https://www.hackerrank.com/domains/mathematics/linear-algebra-foundations
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Eigenvalue of matrix #2 # Basic problems related to eigenvalues. # # https://www.hackerrank.com/challenges/eigenvalue-of-matrix-2/problem # import numpy as np M = np.matrix([[1, 2], [2, 4]]) print(np.linalg.eigvals(M)) I = np.identity(np.linalg.matrix_rank(M)) for λ in np.linalg.eigvals(M): print(np.linalg.det(M - λ * I))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #5 - The 100th Power of a Matrix # Compute the 100<sup>the</sup> power of a given matrix. # # https://www.hackerrank.com/challenges/linear-algebra-foundations-5-the-100th-power-of-a-matrix/problem # import numpy as np a = np.matrix([[1,1,0],[0,1,0],[0,0,1]]) print(a ** 100) """ réponse: 1 100 1 0 1 """
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #10 - Eigenvectors # Compute the EigenVectors of the following 2x2 matrix. # # https://www.hackerrank.com/challenges/linear-algebra-fundamentals-10-eigenvectors/problem # import numpy as np A = np.matrix([[ 0, 1], [-2, -3]]) eig, vec = np.linalg.eig(A) print(eig, vec) v1 = vec[0].A1 v2 = vec[1].A1 print(v1) print(v2) # v1 = sqrt(1/2) -sqrt(2/5) # v1 = -sqrt(1/2) sqrt(4/5) # réponse # cf. http://www.wolframalpha.com/input/?i=%7B%7B0,+1%7D,+%7B-2,+-3%7D%7D # -2 -1
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #7 - The 1000th Power of a Matrix # Compute the 1000th power of the given matrix. # # https://www.hackerrank.com/challenges/linear-algebra-foundations-7-the-1000th-power-of-a-matrix/problem # # solution plus aboutie, en calculant l'exponentiation soi-même def multm(A, B): """ produit matriciel: A * B """ a00, a10, a01, a11 = A b00, b10, b01, b11 = B return [a00 * b00 + a10 * b01, a00 * b10 + a10 * b11, a01 * b00 + a11 * b01, a01 * b10 + a11 * b11] def multv(A, V): """ produit matrice/vecteur: A * V """ a00, a10, a01, a11 = A b0, b1 = V return [a00 * b0 + a10 * b1, a01 * b0 + a11 * b1] def power(M, k): """ fast exponentiation M^k """ P = [1, 0, 0, 1] if k == 0: return P if k == 1: return M while k != 0: if k % 2 == 1: P = multm(P, M) M = multm(M, M) k //= 2 return P A = [-2, -9, 1, 4] B = power(A, 1000) for x in B: print(x)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Determinant of the matrix #3 # Basic problems related to determinants. # # https://www.hackerrank.com/challenges/determinant-of-the-matrix-3/problem # # le déterminant d'une matrice d'ordre 3 est a*e*i+b*f*g+c*d*h-g*e*c-h*f*a-i*d*b # il ne change pas dans la deuxième matrice # réponse: -6
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #3- Matrix Multiplication # Matrix Multiplication of 2x2 Matrices # # https://www.hackerrank.com/challenges/linear-algebra-foundations-3-matrix-multiplication/problem # # 1*4+2*7 = 18 # 1*5+2*8 = 21 # 2*4+3*7 = 29 # 2*5+3*8 = 34 # réponse: 18 21 29 34
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Mathematics](https://www.hackerrank.com/domains/mathematics) Without mathematics, there's nothing you can do. Everything around you is mathematics. Everything around you is numbers. #### [Linear Algebra Foundations](https://www.hackerrank.com/domains/mathematics/linear-algebra-foundations) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Linear Algebra Foundations #1 - Matrix Addition](https://www.hackerrank.com/challenges/linear-algebra-foundations-1)|The basics of linear algebra and matrices as required in Machine Learning.|[text](linear-algebra-foundations-1.txt)|Easy [Linear Algebra Foundations #2 - Matrix Subtraction](https://www.hackerrank.com/challenges/linear-algebra-foundations-1-matrix-subtraction)|The basics of linear algebra and matrices as required in Machine Learning.|[text](linear-algebra-foundations-1-matrix-subtraction.txt)|Easy [Linear Algebra Foundations #3- Matrix Multiplication](https://www.hackerrank.com/challenges/linear-algebra-foundations-3-matrix-multiplication)|Matrix Multiplication of 2x2 Matrices|[Python](linear-algebra-foundations-3-matrix-multiplication.py) [text](linear-algebra-foundations-3-matrix-multiplication.txt)|Easy [Linear Algebra Foundations #4- Matrix Multiplication](https://www.hackerrank.com/challenges/linear-algebra-foundations-4-matrix-multiplication)|Matrix Multiplication of 2x2 Matrices|[Python](linear-algebra-foundations-4-matrix-multiplication.py)|Easy [Linear Algebra Foundations #5 - The 100th Power of a Matrix](https://www.hackerrank.com/challenges/linear-algebra-foundations-5-the-100th-power-of-a-matrix)|Compute the 100<sup>the</sup> power of a given matrix.|[Python](linear-algebra-foundations-5-the-100th-power-of-a-matrix.py)|Medium [Linear Algebra Foundations #6 - An Equation involving Matrices](https://www.hackerrank.com/challenges/linear-algebra-foundations-6-the-nsupthsup-power-of-a-matrix)|Solve an equation involving matrices.|[text](linear-algebra-foundations-6-the-nsupthsup-power-of-a-matrix.txt)|Medium [Linear Algebra Foundations #7 - The 1000th Power of a Matrix](https://www.hackerrank.com/challenges/linear-algebra-foundations-7-the-1000th-power-of-a-matrix)|Compute the 1000th power of the given matrix.|[Python](linear-algebra-foundations-7-the-1000th-power-of-a-matrix.py) [text](linear-algebra-foundations-7-the-1000th-power-of-a-matrix.txt)|Hard [Linear Algebra Foundations #8 - Systems of Equations](https://www.hackerrank.com/challenges/linear-algebra-fundamentals-8-systems-of-equations)|A system of equations with no solutions.|[Python](linear-algebra-fundamentals-8-systems-of-equations.py)|Hard [Linear Algebra Foundations #9 - Eigenvalues](https://www.hackerrank.com/challenges/linear-algebra-fundamentals-9-eigenvalues)|Compute the Eigenvalues of the following 2x2 matrix.|[text](linear-algebra-fundamentals-9-eigenvalues.txt)|Hard [Linear Algebra Foundations #10 - Eigenvectors](https://www.hackerrank.com/challenges/linear-algebra-fundamentals-10-eigenvectors)|Compute the EigenVectors of the following 2x2 matrix.|[Python](linear-algebra-fundamentals-10-eigenvectors.py)|Medium [Determinant of the matrix #1](https://www.hackerrank.com/challenges/determinant-of-the-matrix-1)|Basic problems related to determinants.|[Python](determinant-of-the-matrix-1.py)|Medium [Determinant of the matrix #2](https://www.hackerrank.com/challenges/determinant-of-the-matrix-2)|Basic problems related to determinants.|[text](determinant-of-the-matrix-2.txt)|Hard [Determinant of the matrix #3](https://www.hackerrank.com/challenges/determinant-of-the-matrix-3)|Basic problems related to determinants.|[text](determinant-of-the-matrix-3.txt)|Medium [Eigenvalue of a Matrix I](https://www.hackerrank.com/challenges/eigenvalue-of-matrix-1)|Basic problems related to eigenvalues.|[Python](eigenvalue-of-matrix-1.py)|Hard [Eigenvalue of matrix #2](https://www.hackerrank.com/challenges/eigenvalue-of-matrix-2)|Basic problems related to eigenvalues.|[Python](eigenvalue-of-matrix-2.py)|Hard [Eigenvalue of matrix #3](https://www.hackerrank.com/challenges/eigenvalues-of-matrix-3)|Basic problems related to eigenvalues.|[Python](eigenvalues-of-matrix-3.py)|Hard [Eigenvalue of matrix #4](https://www.hackerrank.com/challenges/eigenvalues-of-matrix-4)|Basic problems related to eigenvalues.|[Python](eigenvalues-of-matrix-4.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #8 - Systems of Equations # A system of equations with no solutions. # # https://www.hackerrank.com/challenges/linear-algebra-fundamentals-8-systems-of-equations/problem # import numpy as np for a in range(-10, 11, 1): M = np.matrix([[a, 1, 2], [1, 2, 1], [2, 1, a]]) if abs(np.linalg.det(M)) < 1e-6: print(a) """ réponse: -1 2 """
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Long Permutation # Determine the n^th element of an infinite permutation! # # https://www.hackerrank.com/challenges/long-permutation/problem # https://www.hackerrank.com/contests/101hack37/challenges/long-permutation # challenge id: 21494 # n, m = map(int, input().split()) p = list(map(int, input().split())) x = 0 while m >= 1: m -= 1 x = p[x] if x >= n: x += m break print(x)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Prime Sum # Represent a number as sum of primes. # # https://www.hackerrank.com/challenges/prime-sum/problem # https://www.hackerrank.com/contests/w3/challenges/prime-sum # challenge id: 2310 # from random import randrange def miller_rabin(n, k=10): if n == 2: return True if n & 1 == 0: return False def check(a, s, d, n): x = pow(a, d, n) if x == 1: return True for i in range(s - 1): if x == n - 1: return True x = pow(x, 2, n) return x == n - 1 s = 0 d = n - 1 while d % 2 == 0: d >>= 1 s += 1 for i in range(k): a = randrange(2, n - 1) if not check(a, s, d, n): return False return True class Crible: """ Crible d'Eratosthène optimisé """ def __init__(self, n_max): self.n_max = n_max self.maximum = n = (n_max - 3) // 2 + 1 self.crible = crible = [False] * (n + 1) self._premiers = None self._phi = None i = 0 while i < n: while i < n: if not crible[i]: break i += 1 k = 3 while True: j = k * i + 3 * (k - 1) // 2 if j >= n: break crible[j] = True k += 2 i += 1 def est_premier(self, n): if n == 2: return True elif n % 2 == 0 or n <= 1: return False else: # n est impair et >= 3 assert n < self.n_max return not self.crible[(n - 3) // 2] N = 1000000 sieve = Crible(N) def is_prime(n): if n < N: return sieve.est_premier(n) else: return miller_rabin(n) def check(n, k): if k == 1: # il faut que n soit premier print("Yes" if is_prime(n) else "No") elif n < 4: # aucune solution print("No") elif k == 2 and n % 2 == 1: # n ne peut être la somme que d'un nombre pair et d'un nombre impair # et pas la somme de deux nombres impairs. # le seul premier pair est 2. # donc si n-2 est premier ok, sinon non print("Yes" if is_prime(n - 2) else "No") elif n % 2 == 0: # 2+2+...+2 valeur minimale de la somme, # sinon conjecture de Goldbach (on a n > 3 ici) print("Yes" if k <= n // 2 else "No") else: # 3+2+2+...+2 valeur minimale de la somme # n-3 est pair, on utilise Goldbach print("Yes" if k - 1 <= (n - 3) // 2 else "No") for _ in range(int(input())): n, k = map(int, input().split()) check(n, k)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Closest Number # What is the closest number? # # https://www.hackerrank.com/challenges/closest-number/problem # def closestNumber(a, b, x): p = int(a ** b) m = (p // x) * x if p - m > m + x - p: return m + x else: return m if __name__ == '__main__': for _ in range(int(input())): a, b, x = map(int, input().split()) result = closestNumber(a, b, x) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Fibonacci Finding (easy) # Find some Fibonacci numbers! # # https://www.hackerrank.com/challenges/fibonacci-finding-easy/problem # MOD = 1000000007 def multm(A, B): """ produit matriciel: A * B """ a00, a10, a01, a11 = A b00, b10, b01, b11 = B return [(a00 * b00 + a10 * b01) % MOD, (a00 * b10 + a10 * b11) % MOD, (a01 * b00 + a11 * b01) % MOD, (a01 * b10 + a11 * b11) % MOD] def multv(A, V): """ produit matrice/vecteur: A * V """ a00, a10, a01, a11 = A b0, b1 = V return [(a00 * b0 + a10 * b1) % MOD, (a01 * b0 + a11 * b1) % MOD] def power(M, k): """ fast exponentiation M^k """ P = [1, 0, 0, 1] if k == 0: return P if k == 1: return M while k != 0: if k % 2 == 1: P = multm(P, M) M = multm(M, M) k //= 2 return P # http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form # Fn = A^n * F0 # avec Fn[f(n+1) f(n)) # et A = [[1 1][1 0]] for _ in range(int(input())): a, b, n = map(int, input().split()) A = [1, 1, 1, 0] An = power(A, n) F0 = [b, a] Fn = multv(An, F0) print(Fn[1])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Easy math # Help Johnny in figuring out the value of Y # # https://www.hackerrank.com/challenges/easy-math/problem # https://www.hackerrank.com/contests/101oct13/challenges/easy-math # challenge id: 1138 # for _ in range(int(input())): n = x = int(input()) n2 = 0 while x % 2 == 0: n2 += 1 x //= 2 # le nombre de 0 est le nombre de 5 n5 = 0 while x % 5 == 0: n5 += 1 x //= 5 if False: # nota: on ne doit pas être très loin de l'utilisation # de l'indicatrice d'Euler puisque: # a^φ(n) ≡ 1 mod n avec a,n coprime # en prenant a=10 et n=x, ils sont coprime # et 10^n-1 = 9999...9 ≡ 0 mod x # soit 9/4 * 44444...44 ≡ 0 mod x # à un coefficient près (que je ne connais pas), φ(x) = nombre de 4 a = EulerPhi(x) else: y = 1 a = 1 while y % x != 0: y = (y * 10 + 1) % x a += 1 # le nombre de 4 est le nombre de 1, i.e. a b = n5 if n2 - n5 > 2: b += n2 - n5 - 2 print(2 * a + b)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > The Chosen One # Given a list of integers, find and print an integer that is a divisor of all but one integer in the list. # # https://www.hackerrank.com/challenges/the-chosen-one/problem # from math import gcd n = int(input()) A = list(map(int, input().split())) if n == 1: print(A[0] + 1) else: gauche = [0] * n droite = [0] * n # calcul du gcd de [A0..Ai] dans gauche[i] g = 0 for i in range(n): g = gauche[i] = gcd(g, A[i]) # calcul du gcd de [Ai..An] dans droite[i] g = 0 for i in range(n - 1, -1, -1): g = droite[i] = gcd(g, A[i]) # avec les deux tablaaux ci-dessus, on peut calculer le gcd de {A} \ A[i] # gcd(gauche[i-1]), droite[i+1]) # si ce gcd ne divise pas A[i] on a trouvé une solution for i in range(n): if i == 0: g = droite[i + 1] elif i == n - 1: g = gauche[i - 1] else: g = gcd(gauche[i - 1], droite[i + 1]) if A[i] % g != 0: print(g) break
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Manasa loves Maths # Find out if any permutation of the given number is divisible by 8. # # https://www.hackerrank.com/challenges/manasa-loves-maths/problem # https://www.hackerrank.com/contests/mar14/challenges/manasa-loves-maths # challenge id: 1892 # # here is my algorithm: # if len(n) < 3: test directly with % # if len(n) >= 3: # A number is divisble by 8 if its three last digits form a number that is # divisible by 8. In other words, a permutation of the input is divisible # by 8 if the input contains the digits of a 3-digit number divisible by 8. # Thus, no need to compute all the permutations. # Step 1: # precalculate all the 125 3-digit numbers divisible by 8 and compute # a kind of signature: each unique digit is a bit (30 bits in total) # 0 1 2 3 4 5 6 7 8 9 # ... ... ... ... ... ... ... ... ... ... # ^^^ # 001 if there is one 0 # 011 if there is two 0 # 111 if there is three 0 # Step 2: # compute the same signature (limiting digit count to 3) for the tests # and test against the precomputed values div8 = set() for i in range(0, 1000, 8): count = [0] * 10 count[i % 10] += 1 count[(i // 10) % 10] += 1 count[(i // 100) % 10] += 1 b = 0 for j in count: b = (b << 3) + ((1 << j) - 1) div8.add(b) for _ in range(int(input())): n = input() ok = False if len(n) == 1: ok = int(n) % 8 == 0 elif len(n) == 2: ok = (int(n) % 8 == 0) or (int(n[::-1]) % 8 == 0) else: count = [0] * 10 for c in list(n): d = int(c) if count[d] < 3: count[d] += 1 b = 0 for j in count: b = (b << 3) + ((1 << j) - 1) for i in div8: if (b & i) == i: ok = "YES" break print("YES" if ok else "NO")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Fibonacci GCD # Find gcd for n fibonacci numbers. # # https://www.hackerrank.com/challenges/fibonacci-gcd/problem # https://www.hackerrank.com/contests/infinitum9/challenges/fibonacci-gcd # challenge id: 4503 # from math import gcd MOD = 1000000007 def multm(A, B): """ produit matriciel: A * B """ a00, a10, a01, a11 = A b00, b10, b01, b11 = B return [(a00 * b00 + a10 * b01) % MOD, (a00 * b10 + a10 * b11) % MOD, (a01 * b00 + a11 * b01) % MOD, (a01 * b10 + a11 * b11) % MOD] def multv(A, V): """ produit matrice/vecteur: A * V """ a00, a10, a01, a11 = A b0, b1 = V return [(a00 * b0 + a10 * b1) % MOD, (a01 * b0 + a11 * b1) % MOD] def power(M, k): """ fast exponentiation M^k """ P = [1, 0, 0, 1] if k == 0: return P if k == 1: return M while k != 0: if k % 2 == 1: P = multm(P, M) M = multm(M, M) k //= 2 return P # on utilise la propriété suivante: # gcd(F(a), F(b)) = F(gcd(a, b)) # calcul du gcd(aᵢ) g = 0 n = int(input()) for i in range(n): g = gcd(g, int(input())) # calcul de F(g) (cf. https://www.hackerrank.com/challenges/fibonacci-finding-easy) # http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form # Fn = A^n * F0 # avec Fn[f(n+1) f(n)) # et A = [[1 1][1 0]] A = [1, 1, 1, 0] An = power(A, g) F0 = [1, 0] Fn = multv(An, F0) print(Fn[1])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Power of large numbers # How much does Hackerland coach pay to get Cristiano Ronaldo to play for his team? # # https://www.hackerrank.com/challenges/power-of-large-numbers/problem # def powmod(x, k, MOD): """ fast exponentiation x^k % MOD """ p = 1 if k == 0: return p if k == 1: return x while k != 0: if k % 2 == 1: p = (p * x) % MOD x = (x * x) % MOD k //= 2 return p MOD = 1000000007 for _ in range(int(input())): sx, sy = input().split() # x = x modulo MOD x = 0 for d in sx: x = (x * 10 + int(d)) % MOD # y = y modulo (MOD - 1) y = 0 for d in sy: y = (y * 10 + int(d)) % (MOD - 1) # petit théorème de Fermat: https://fr.wikipedia.org/wiki/Petit_théorème_de_Fermat # p premier, m = n (mod p - 1) # alors a^m = a^n (mod p) # application ici: en calculant x^(y mod (p-1)) on a une valeur exacte modulo p print(powmod(x, y, MOD))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Minimal Distance to Pi https://www.hackerrank.com/challenges/minimal-distance-to-pi/problem https://www.hackerrank.com/contests/w29/challenges/minimal-distance-to-pi """ from fractions import Fraction #q1, q2 = 756624603896972, 837574890139508 q1, q2 = map(int, input().split()) """ BRUTE FORCE pi50 = 314159265358979323846264338327950288419716939937515 base = 10 ** 50 rmin = 0 rmax = 0 for i in range(d0, d1 + 1): q, r = divmod(i * pi50, base) # print("{:<8} {:<8} {:<50} {:<50}".format(i, q, r, 10 ** 50 - r)) print(r / base) if rmin == 0 or r < rmin: rmin = r nd1 = (q, i) r = base - r if rmin == 0 or r < rmin: rmin = r nd1 = (q + 1, i) print("{}/{}".format(nd1[0], nd1[1])) """ # https://oeis.org/A001203 a001203 = [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, 1, 84, 2, 1, 1, 15, 3, 13, 1, 4, 2, 6, 6, 99, 1, 2, 2, 6, 3, 5, 1, 1, 6, 8, 1, 7, 1, 2, 3, 7, 1, 2, 1, 1, 12, 1, 1, 1, 3, 1, 1, 8, 1, 1, 2, 1, 6, 1, 1, 5, 2, 2, 3, 1, 2, 4, 4, 16, 1, 161, 45, 1, 22, 1, 2, 2, 1, 4, 1, 2, 24, 1, 2, 1, 3, 1, 2, 1] def fraction_continue(f, a, i): ai = a[0] if i == 0 else a[1 + (i - 1) % (len(a) - 1)] if f == 0: return Fraction(ai) return ai + 1 / f def calc_fraction_continue(a, k): f = Fraction(0) while k > 0: k -= 1 f = fraction_continue(f, a, k) return f # http://www.libragold.com/blog/2017/03/minimal-distance-to-pi/ P = calc_fraction_continue(a001203, 30) - 3 # find endpoints of Farey intervals a, b, c, d = 0, 1, 1, 1 farey = [(a,b),(c,d)] while True: f = b + d if f > q2 - q1: break e = a + c farey.append((e, f)) if P < Fraction(e, f): c, d = e, f else: a, b = e, f p_min = int(P * q1) # increase p_min/min by fractions in farey while q1 <= q2: c, d = 0, 0 for a, b in farey: if q1 + b > q2: break if abs(Fraction(p_min + a, q1 + b).real - P) < abs(Fraction(p_min, q1).real - P): c, d = a, b break if d == 0: break p_min += c q1 += d print("{}/{}".format(p_min + 3 * q1, q1))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Sherlock Puzzle # Help Sherlock get close to his Arch Nemesis, Jim Moriarty. # # https://www.hackerrank.com/challenges/sherlock-puzzle/problem # https://www.hackerrank.com/contests/sep13/challenges/sherlock-puzzle # challenge id: 836 # from bisect import bisect_left K, S = input().split() K = int(K) n = len(S) s = [0] * (n + 1) a = [0] * (n + 1) a[0] = (0, 0) for i in range(n): s[i + 1] = s[i] - 3 * (S[i] == '1') + 2 * (S[i] == '0') a[i + 1] = (s[i + 1], i + 1) a.sort() dp = [0] * (n + 1) dp[0] = a[0][1] for i in range(n): dp[i + 1] = max(dp[i], a[i + 1][1]) answer = 0 for i in range(n): dx = a[0][0] - s[i] if s[n] <= 0: x = K - 1 if dx + s[n] * x > 0: continue elif dx > 0: continue else: x = min(K - 1, -dx // s[n]) v = x * s[n] - s[i] p = bisect_left(a, (-v + 1, 0)) - 1 answer = max(answer, dp[p] - i + x * n) print(answer)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Mathematics > Number Theory > Largest Non-Coprime Submatrix // Given a matrix find the largest coprime submatrix. // // https://www.hackerrank.com/challenges/largest-coprime-submatrix/problem // challenge id: 781 // #include <bits/stdc++.h> using namespace std; // solution: brute force... int gcd(int u, int v) { while (v != 0) { int r = u % v; u = v; v = r; } return u; } int main() { int matrix[200][200]; size_t n, m; cin >> n >> m; for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { cin >> matrix[i][j]; } } size_t r = 0; for (size_t x1 = 0; x1 < n; ++x1) { for (size_t y1 = 0; y1 < m; ++y1) { if (r > (n - x1) * (m - y1)) break; // gcd entre (x1,y1) et (x2,y2) int sub_gcd[200] = {0}; for (size_t x2 = x1; x2 < n; ++x2) { int g = 0; for (size_t y2 = y1; y2 < m; ++y2) { g = gcd(gcd(g, matrix[x2][y2]), sub_gcd[y2]); sub_gcd[y2] = g; if (g == 1) break; r = max(r, (x2 - x1 + 1) * (y2 - y1 + 1)); } } } } cout << r << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Manasa and Factorials # Think about number of zeros in k! # # https://www.hackerrank.com/challenges/manasa-and-factorials/problem # https://www.hackerrank.com/contests/infinitum-apr14/challenges/manasa-and-factorials # def count5(n): sum = 0 product = 1 while product < n: product *= 5 sum += n // product return sum for _ in range(int(input())): n = int(input()) # chaque mutiple de 5 ajoute un 0 (en fait de 2 et 5 mais il y a plus de mutiples de 2 que de 5 dans n!) # et plus généralement: # chaque mutiple de 5^k ajoute k 0 # la réponse est entre 4n et 5n # et multiple de 5 j = (4 * n + 4) // 5 * 5 while count5(j) < n: j += 5 print(j)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Megaprime Numbers # Count the number of primes in a given range that consist only of prime digits. # # https://www.hackerrank.com/challenges/megaprime-numbers/problem # https://www.hackerrank.com/contests/w29/challenges/megaprime-numbers # challenge id: 33596 # from random import randrange import sys def miller_rabin(n, k=10): if n == 2 or n == 3 or n == 5 or n == 7: return True if n % 2 == 0 or n % 5 == 0: return False def check(a, s, d, n): x = pow(a, d, n) if x == 1: return True for i in range(s - 1): if x == n - 1: return True x = pow(x, 2, n) return x == n - 1 s = 0 d = n - 1 while d % 2 == 0: d >>= 1 s += 1 for i in range(k): a = randrange(2, n - 1) if not check(a, s, d, n): return False return True def to4(q): digits = [2, 3, 5, 7] q += 1 e = 1 n = 0 while q != 0: q, r = divmod(q - 1, 4) n += e * digits[r] e *= 10 return n def from4(s): digits = [0, 0, 0, 1, 0, 2, 0, 3, 0, 0] n = -1 for d in str(s): d = digits[int(d)] n = 4 * (n + 1) + d return n start, end = map(int, input().split()) # find the number below start in 'base-2357' carry = False start4 = -1 for d in str(start): if carry: d = 3 else: d = int(d) if d >= 7: d = 3 elif d >= 5: d = 2 elif d >= 3: d = 1 elif d == 2: d = 0 else: d = 3 carry = True start4 -= 1 start4 = 4 * (start4 + 1) + d if start4 == -1: start4 = 0 # then iterate through numbers between start to end answer = 0 i = start4 while True: n = to4(i) i += 1 if n > end: break if n < start: continue if miller_rabin(n): answer += 1 print(answer)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Mehta and his Laziness # How will Mehta do these calculations? # # https://www.hackerrank.com/challenges/mehta-and-his-laziness/problem # https://www.hackerrank.com/contests/infinitum-sep14/challenges/mehta-and-his-laziness # # le testcase 1 est en timeout avec Python3, ok avec pypy3 # j'ai dû rater une optimisation :-/ from fractions import Fraction MAX = 1000000 even_squares = [False] * (MAX + 1) for i in range(2, MAX, 2): x = i * i if x > MAX: break even_squares[x] = True def diviseurs(n): div = [1] i = 2 while i * i <= n: q, r = divmod(n, i) if r == 0: div.append(i) if i != q: div.append(q) i += 1 if n != 1: div.append(n) return div def even_squares_divisors(n): nb = 1 # 1 est diviseur even = 0 i = 2 while i * i <= n: q, r = divmod(n, i) if r == 0: nb += 1 if even_squares[i]: even += 1 if i != q: nb += 1 if even_squares[q]: even += 1 i += 1 return Fraction(even, nb) for _ in range(int(input())): n = int(input()) # d = diviseurs(n) # x = sum(1 for i in d if even_squares[i]) # print(n, d, x, Fraction(x, len(d))) # print(Fraction(x, len(d))) print(even_squares_divisors(n))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Twins # How many pairs of twins can you find? # # https://www.hackerrank.com/challenges/twins/problem # https://www.hackerrank.com/contests/w26/challenges/twins # # algo sans crible segemnté, peu efficace mais suffisant s'il est lancé en pypy3 # timeout en python3 :( class bitset: """ Implémentation d'un bitset à stockage optimisé """ def __init__(self, taille): self.bits = bytearray((taille + 7) // 8) def set(self, pos): """ poitionne le bit `pos` à `val` """ self.bits[pos // 8] |= (1 << (pos % 8)) def is_unset(self, pos): """ lit l'état du bit `pos` """ return (self.bits[pos // 8] & (1 << (pos % 8))) == 0 class Crible: """ Crible d'Eratosthène optimisé """ def __init__(self, n_max): self.n_max = n_max self.maximum = n = (n_max - 3) // 2 + 1 self.crible = crible = bitset(n) self._premiers = None i = 0 while i < n: while i < n: if crible.is_unset(i): break i += 1 k = 3 while True: j = k * i + 3 * (k - 1) // 2 if j >= n: break crible.set(j) k += 2 i += 1 premiers = [2] for i in range(1, self.maximum + 1): if self.crible.is_unset(i - 1): premiers.append(2 * i + 1) self._premiers = premiers def liste(self): return self._premiers n, m = map(int, input().split()) primes = Crible(int(m ** 0.5) + 2).liste()[1:] count = 0 last_prime = -3 n = max((n // 2) * 2 + 1, 3) for i in range(n, m + 1, 2): is_prime = True for p in primes: if i == p: break if i % p == 0: is_prime = False break if not is_prime: continue if i - last_prime == 2: count += 1 last_prime = i print(count)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Number of zero-xor subsets # How many subsets with zero xor are here? # # https://www.hackerrank.com/challenges/number-of-subsets/problem # https://www.hackerrank.com/contests/infinitum10/challenges/number-of-subsets # challenge id: 4731 # MOD = 1000000007 # la réponse est 2^(2^n - n) for _ in range(int(input())): n = int(input()) # généralisation du petit théorème de Fermat e = (pow(2, n, MOD - 1) - n) % (MOD - 1) r = pow(2, e, MOD) print(r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
add_hackerrank_py(sherlock-and-gcd.py) add_hackerrank_py(minimal-distance-to-pi.py) add_hackerrank_py(identify-smith-numbers.py) add_hackerrank_py(constructing-a-number.py) add_hackerrank_py(littlepandapower.py) add_hackerrank_py(fibonacci-finding-easy.py) add_hackerrank_py(closest-number.py) add_hackerrank_py(eulers-criterion.py) add_hackerrank_py(john-and-gcd-list.py) add_hackerrank_py(easy-gcd-1.py) add_hackerrank_py(the-chosen-one.py) add_hackerrank_py(power-of-large-numbers.py) add_hackerrank_py(manasa-and-factorials.py) add_hackerrank_py(primitive-problem.py) add_hackerrank_py(twins.py) add_hackerrank_py(mehta-and-his-laziness.py) add_hackerrank_py(help-mike.py) add_hackerrank_py(manasa-loves-maths.py) add_hackerrank_py(dance-class.py) add_hackerrank_py(akhil-and-gf.py) add_hackerrank_py(salary-blues.py) add_hackerrank(little-chammys-huge-donation little-chammys-huge-donation.cpp) add_hackerrank_py(number-of-subsets.py) add_hackerrank_py(cheese-and-random-toppings.py) add_hackerrank(breaking-sticks breaking-sticks.cpp) add_hackerrank_py(easy-math.py) add_hackerrank(lucy-and-flowers lucy-and-flowers.cpp) add_hackerrank_py(binomial-coefficients.py) add_hackerrank(pairs-again pairs-again.cpp) add_hackerrank(largest-coprime-submatrix largest-coprime-submatrix.cpp) add_hackerrank_py(ncr.py) set_tests_properties(pairs-again PROPERTIES TIMEOUT 120) set_tests_properties(easy-math.py PROPERTIES TIMEOUT 120) add_hackerrank_py(prime-sum.py) add_hackerrank_py(fibonacci-gcd.py) add_hackerrank_py(divisor-exploration-2.py) add_hackerrank_py(strange-numbers.py) add_hackerrank_py(divisor-exploration-3.py) add_hackerrank(divisor-exploration-3 divisor-exploration-3.cpp) add_hackerrank_py(equations.py) add_hackerrank_py(superpowers.py) add_hackerrank_py(divisibility-of-power.py) add_hackerrank_py(devu-police.py) add_hackerrank_py(long-permutation.py) add_hackerrank_py(megaprime-numbers.py) add_hackerrank_py(sherlock-puzzle.py) add_hackerrank_py(divisor-exploration.py)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Salary Blues # Help manager of HackerX company to normalize salaries. # # https://www.hackerrank.com/challenges/salary-blues/problem # https://www.hackerrank.com/contests/infinitum-apr14/challenges/salary-blues # challenge id: 1833 # from math import gcd n, q = map(int, input().split()) A = list(map(int, input().split())) a0 = A[0] for i in range(1, len(A)): A[i] -= a0 g = A[1] for i in range(2, len(A)): g = gcd(g, A[i]) for _ in range(q): k = int(input()) if len(A) == 1: print(a0 + k) else: print(gcd(g, a0 + k))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Mathematics > Number Theory > Divisor Exploration 3 // Find the value given at the root of a tree constructing by the given rules. // // https://www.hackerrank.com/challenges/divisor-exploration-3/problem // https://www.hackerrank.com/contests/infinitum18/challenges/divisor-exploration-3 // challenge id: 12630 // // C++ version, I can't find a way to optimize these instructions // num = (p * num * c_den - c_num * den) % MOD // den = (den * (p - 1) * c_den) % MOD // in Python (it's ok with numba.jit...) #include <bits/stdc++.h> using namespace std; #define MOD 1000000007 vector<int64_t> primes; void init_primes() { int64_t PRIME_1000 = 7919; vector<bool> sieve(1 + PRIME_1000, true); primes.reserve(1000); for (int64_t n = 2; n <= PRIME_1000; ++n) { if (sieve[n]) { primes.push_back(n); for (int64_t i = n; i <= PRIME_1000; i += n) sieve[i] = false; } } } int64_t modinv(int64_t a, int64_t b) { int64_t t, nt, r, nr, q, tmp; if (b < 0) b = -b; if (a < 0) a = b - (-a % b); t = 0; nt = 1; r = b; nr = a % b; while (nr != 0) { q = r/nr; tmp = nt; nt = t - q*nt; t = tmp; tmp = nr; nr = r - q*nr; r = tmp; } if (r > 1) return -1; /* No inverse */ if (t < 0) t += b; return t; } int64_t fast_f(int64_t i, int64_t p, int64_t a) { int64_t num, den; int64_t c_num, c_den; num = 1; den = 1; for (int64_t i = 0; i < a; ++i) num = (num * p) % MOD; c_num = 1; c_den = 1; for (int64_t j = 2; j <= i; ++j) { if (j > 2) { c_num = (c_num * (a + j - 2)) % MOD; c_den = (c_den * (j - 2)) % MOD; } num = (p * ((num * c_den) % MOD) % MOD - c_num * den) % MOD; if (num < 0) num += MOD; den = (((den * (p - 1)) % MOD) * c_den) % MOD; } num = (num * modinv(den, MOD)) % MOD; return num; } int64_t solve(int64_t m, int64_t a, int64_t d) { int64_t res = 1; for (int64_t i = 0; i < m; ++i) res = (res * fast_f(d, primes[i], a + i + 1)) % MOD; return res; } int main() { int64_t m, a, d; int t; init_primes(); cin >> t; while (t--) { cin >> m >> a >> d; cout << solve(m, a, d) << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Superpowers of 2 # Just another numbers problem... # # https://www.hackerrank.com/challenges/superpowers/problem # https://www.hackerrank.com/contests/101hack20/challenges/superpowers # challenge id: 5505 # a, b = map(int, input().split()) print(pow(2, pow(2, a), b))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Mathematics > Number Theory > Lucy and Flowers // Help Lucy's father with a computation involving flowers // // https://www.hackerrank.com/challenges/lucy-and-flowers/problem // https://www.hackerrank.com/contests/w4/challenges/lucy-and-flowers // challenge id: 2414 // #include <bits/stdc++.h> using namespace std; constexpr unsigned MAX = 5001; constexpr unsigned MOD = 1000000009; unsigned catalan[MAX]; unsigned C[MAX][MAX]; unsigned mult(unsigned a, unsigned b, unsigned mod) { unsigned long long la = a; unsigned long long lb = b; return (unsigned)((la * lb) % mod); } void precompute() { // calcule les nombres de Catalan // https://oeis.org/A000108 catalan[0] = 1; catalan[1] = 1; for (unsigned i = 2; i < MAX; ++i) { unsigned c = 0; for (unsigned j = 1; j <= i; j++) c = (c + mult(catalan[j - 1], catalan[i - j], MOD)) % MOD; catalan[i] = c; } // Caculate value of Binomial Coefficient in bottom up manner //https://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/ memset(C, 0, sizeof(C)); for (unsigned i = 0; i < MAX; i++) { for (unsigned j = 0; j <= i; j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previosly stored values else C[i][j] = (C[i-1][j-1] + C[i-1][j]) % MOD; } } } // la solution est Σ C(n, i) * catalan(i) // unsigned solve(unsigned n) { unsigned r = 0; for (unsigned i = 1; i <= n; i++) r = (r + mult(C[n][i], catalan[i], MOD)) % MOD; return r; } int main() { precompute(); int t; cin >> t; while (t--) { unsigned n; cin >> n; cout << solve(n) << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Divisor Exploration # Find and print the number of divisors for each dataset. # # https://www.hackerrank.com/challenges/divisor-exploration/problem # https://www.hackerrank.com/contests/infinitum16/challenges/divisor-exploration # challenge id: 11996 # #!/bin/python3 import os import sys # (template_head) ---------------------------------------------------------------------- # p prime # σ₀(pⁿ) = n+1 # ∑ σ₀(pⁿ) = 1+2+...+(n+1) = (n+1)(n+2)/2 = tri(n+1) # ∑ σ₀(p₁ⁿ¹ ∙ p₂ⁿ²) = tri(n₁) ∙ tri(n₂) # ∑ σ₀(∏ pᵢⁿⁱ) = ∏ tri(nᵢ) # brute force is too long : O(10⁵ ∙ 10⁵) # precompute P(n) = ∏ tri(i) (i ≤ n) with n ≤ m(max) + a(max) = 2∙10⁵ # answer is P(m+a+1) / P(a+1) = P(m+a+1) * modinv(P(a+1), MOD) MOD = 1000000007 def egcd(b, a): """ algortihme d'Euclide étendu: (g, x, y) tel que ax + by = g = gcd(a, b) """ # https://fr.wikipedia.org/wiki/Algorithme_d%27Euclide_étendu x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def modinv(a, m): """ modular inverse avec Bachet-Bézout """ # https://fr.wikipedia.org/wiki/Théorème_de_Bachet-Bézout g, x, _ = egcd(a, m) assert g == 1 return x % m MAX = 100000 + 100000 P = [1] * (MAX + 1) invP = [0] * (MAX + 1) for i in range(1, MAX + 1): t = i * (i + 1) // 2 P[i] = (t * P[i - 1]) % MOD invP[i] = modinv(P[i], MOD) # Complete the solve function below. def solve(m, a): """ brute force p = 1 for i in range(a + 2, a + m + 2): p *= i * (i + 1) // 2 p %= MOD return p """ return (P[m + a + 1] * invP[a + 1]) % MOD # (template_tail) ---------------------------------------------------------------------- if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') d = int(input()) for d_itr in range(d): ma = input().split() m = int(ma[0]) a = int(ma[1]) result = solve(m, a) fptr.write(str(result) + '\n') fptr.close()
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Little Panda Power # Compute A^B mod X # # https://www.hackerrank.com/challenges/littlepandapower/problem # def egcd(b, a): """ return a triple (g, x, y), such that ax + by = g = gcd(a, b) """ x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def mulinv(b, m): """ modular multiplicative inverse """ g, x, _ = egcd(b, m) if g == 1: return x % m def powmod(x, k, m): """ fast exponentiation x^k % m """ if k < 0: x = mulinv(x, m) k = -k p = 1 if k == 0: return p if k == 1: return x while k != 0: if k % 2 == 1: p = (p * x) % m x = (x * x) % m k //= 2 return p for _ in range(int(input())): a, b, m = map(int, input().split()) print(powmod(a, b, m))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Mathematics > Number Theory > Breaking Sticks // Find the length of the longest sequence of moves. // // https://www.hackerrank.com/challenges/breaking-sticks/problem // https://www.hackerrank.com/contests/world-codesprint-12/challenges/breaking-sticks // challenge id: 30186 // #include <bits/stdc++.h> using namespace std; long single_bar(long n) { long moves = 1; // décomposition en facteurs premiers // et calcul du nombre de "mouvements" au fur et à mesure long i = 2; while (i * i <= n) { while (n % i == 0) { n /= i; moves = moves * i + 1; } i += (i >= 3) ? 2 : 1; } if (n > 1) moves = moves * n + 1; return moves; } long longestSequence(const vector<long>& a) { long moves = 0; for (auto n : a) { moves += single_bar(n); } return moves; } int main() { vector<long> a; int n; cin >> n; while (n--) { long x; cin >> x; a.push_back(x); } cout << longestSequence(a) << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Cheese and Random Toppings # How many ways are there to choose exactly R toppings from N toppings? # # https://www.hackerrank.com/challenges/cheese-and-random-toppings/problem # https://www.hackerrank.com/contests/infinitum10/challenges/cheese-and-random-toppings # challenge id: 6061 # # solution # 1. décomposer M en facteurs premiers : {pi} # 2. calculer ai = C(n,r) % pi avec le théorème de Lucas https://fr.wikipedia.org/wiki/Théorème_de_Lucas # on a: ai = C(n,r) % pi # 3. utiliser Bachet-Bezout puis le théorème des restes chinois https://fr.wikipedia.org/wiki/Théorème_des_restes_chinois # x ≡ ai (mod pi) # x = Σ ai∙(m / pi) # 4. x est notre solution import math def nCk(n, k): """ coefficient binomial (ou nombre de combinaisons) """ if n < k: return 0 return math.factorial(n) // math.factorial(k) // math.factorial(n - k) def decompose(n): """ décomposition d'un nombre en facteurs premiers """ facteurs = {} i = 2 while i * i <= n: while n % i == 0: n = n // i facteurs[i] = facteurs.get(i, 0) + 1 if i >= 3: i += 2 else: i += 1 if n > 1: facteurs[n] = facteurs.get(n, 0) + 1 return facteurs def base(x, b): """ calcule les chiffres de en base b """ d = [] while x != 0: x, r = divmod(x, b) d.append(r) return d def lucas(m, n, p): """ théorème de Lucas """ M = base(m, p) N = base(n, p) C = 1 # nota: si m et n ont un nombre de chiffres différents, pas grave # puisque nCr(x,0)=1 : le produit ne change donc pas for mi, ni in zip(M, N): C *= nCk(mi, ni) % p C %= p return C def egcd(b, a): """ algortihme d'Euclide étendu: (g, x, y) tel que ax + by = g = gcd(a, b) """ x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def nCk_mod(n, r, m): """ calcule C(n, r) % m avec m square-free """ if m < 2: return 0 p = decompose(m) assert set(p.values()) == set({1}) p = list(p.keys()) x = 0 for pi in p: ai = lucas(n, r, pi) _, _, v = egcd(pi, m // pi) x += ai * v * (m // pi) return x % m # assert nCk_mod(20, 6, 210) == 120 for _ in range(int(input())): n, r, m = map(int, input().split()) print(nCk_mod(n, r, m))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Help Mike # Help Mike attend the NSA meeting # # https://www.hackerrank.com/challenges/help-mike/problem # https://www.hackerrank.com/contests/sep13/challenges/help-mike # challenge id: 803 # for _ in range(int(input())): n, k = map(int, input().split()) q, r = divmod(n, k) nb_pairs = k * (q - 1) * q // 2 + (r + (k - 1) // 2) * q if r > k // 2: nb_pairs += r - k // 2 print(nb_pairs)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > John and GCD list # Help John in making a list from GCD list # # https://www.hackerrank.com/challenges/john-and-gcd-list/problem # import math import functools def gcd(*numbers): """ greatest common divisor """ return functools.reduce(math.gcd, numbers) def lcm(*numbers): """ least common multiple """ return functools.reduce(lambda a, b: (a * b) // gcd(a, b), numbers, 1) # la réponse est le ppcm "glissant" des Ai for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) x = A[0] B = [x] i = 1 while i < n: y = A[i] B.append(lcm(x, y)) x = y i += 1 B.append(A[-1]) print(*B)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Strange numbers # How many strange numbers belong to interval [L, R]? # # https://www.hackerrank.com/challenges/strange-numbers/problem # https://www.hackerrank.com/contests/w11/challenges/strange-numbers # challenge id: 3082 # # la grosse astuce consiste à prendre le problème à l'envers: # -> c'est facile de tester si un nombre est «strange» # -> on en déduit comment ils sont construits # problème amusant mais pas très mathématique def forensic(): """ brute force / comprendre le problème ... """ def is_strange(i): l = len(str(i)) if l == 1: return True if i % l != 0: return False return is_strange(i // l) def construction(i): s = str(i) l = len(s) if l == 1: return "1" + " (" + s + ")" return str(l) + " " + construction(i // l) n = 0 l = 0 for i in range(100, 100000): if is_strange(i): if l != len(str(i)): l = len(str(i)) n = 0 n += 1 print("{:3} {:10} {}".format(n, i, construction(i))) # résolution du challenge stranges = [] def make_strange(n): """ construction de tous les nombres «strange» de longueur ≤ 18 à partir de n """ stranges.append(n) l = len(str(n)) if l > 18: return for i in range(l + 1, l + 5): m = n while len(str(m * i)) == i: m *= i make_strange(m) for n in range(0, 10): make_strange(n) stranges.sort() # c'est parti ! if __name__ == '__main__': for _ in range(int(input())): L, R = map(int, input().split()) print(sum(1 for i in stranges if L <= i <= R))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Equations # Find the number of positive integral solutions for an equation. # # https://www.hackerrank.com/challenges/equations/problem # challenge id: 39 # # changement de variable: # 1/x + 1/y = 1/n! (1) # ⇒ (x+y)/(x∙y) = 1/n! # ⇒ n!(x+y) = x∙y # ⇒ xy - x∙n! - y∙n! + n!² = n!² # ⇒ (x - n!)(y - n!) = n!² # ⇒ x'∙y' = n!² # donc le nombre de solutions de (1) est le nombre de diviseurs de n!² primes = [] sieve = [True] * 1000001 for n in range(2, 1000001): if sieve[n]: primes.append(n) # supprime les mutiples de n for i in range(2 * n, 1000001, n): sieve[i] = False # l'exposant de p premier dans n! est ep = ∑ n/p^i # n! = ∏ p^ep # le nombre de diviseurs de n! est donc ∏ (ep + 1) # n!² = ∏ p^(2*ep) # le nombre de diviseurs de n!² est donc ∏ (2*ep + 1) n = int(input()) r = 1 for p in primes: ep = 0 i = p while True: e = n // i if e == 0: break ep += e i *= p r *= (2 * ep + 1) r %= 1000007 print(r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Sherlock and GCD # Help Sherlock in finding the subset. # # https://www.hackerrank.com/challenges/sherlock-and-gcd/problem # from math import gcd def verif(a): d = a[0] for i in range(1, len(a)): d = gcd(d, a[i]) if d == 1: return "YES" return "NO" for i in range(int(input())): input() a = list(map(int, input().split())) print(verif(a))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Devu Vs Police # Help Devu escape from police # # https://www.hackerrank.com/challenges/devu-police/problem # https://www.hackerrank.com/contests/infinitum-mar14/challenges/devu-police # challenge id: 1050 # def EulerPhi(n): """ calcul de l'Indicatrice d'Euler φ(n) ou totient(n) """ phi = n i = 2 while i * i <= n: if n % i == 0: phi -= phi // i while n % i == 0: n = n // i if i != 2: i += 2 else: i += 1 if n > 1: phi -= phi // n return phi def solve(n1, k1, n2, k2, n): if k1 == 0 or (n2 == 0 and k2 != 0): # exponent is 0 return pow(n1, 0, n) if n2 == 1 or k2 == 0: # n2^k2 = 1 return pow(n1, k1, n) if n1 == 0 or n1 % n == 0: # exponent is not 0 return 0 if k2 == 1: # other trivial case return pow(n1, k1 * n2, n) # Euler's theorem phi = EulerPhi(n) e = pow(n2, k2, phi) + phi return pow(pow(n1, k1, n), e, n) t = int(input()) for _ in range(t): n1, k1, n2, k2, n = map(int, input().split()) print(solve(n1, k1, n2, k2, n))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Constructing a Number # Construct a number divisible by 3 from the given numbers by reordering their digits. # # https://www.hackerrank.com/challenges/constructing-a-number/problem # def canConstruct(a): # Return "Yes" or "No" denoting whether you can construct the required number. s = sum(sum(int(d) for d in str(i)) for i in a) return "Yes" if s % 3 == 0 else "No" if __name__ == "__main__": t = int(input().strip()) for a0 in range(t): n = int(input().strip()) a = list(map(int, input().strip().split(' '))) result = canConstruct(a) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Mathematics > Number Theory > Little Ashish's Huge Donation // Help Ashish calculate donations. // // https://www.hackerrank.com/challenges/little-chammys-huge-donation/problem // https://www.hackerrank.com/contests/infinitum-sep14/challenges/little-chammys-huge-donation // challenge id: 3334 // #include <bits/stdc++.h> using namespace std; // note: sum i^2 from i=1 to n = 1/6 n (1 + n) (1 + 2 n) int main() { int t; unsigned long i, x; vector<unsigned long> values; values.resize(310723); // 310723 = solution de sum(i^2) = 10^16 for (i = 1; ; ++i) { x = i * (i + 1) * (2 * i + 1) / 6; if (x > 10000000000000000) break; values[i] = x; } cin >> t; while (t--) { cin >> x; auto i = upper_bound(values.cbegin(), values.cend(), x); --i; cout << (i - values.cbegin()) << endl; } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Divisibility of Power # Divisibility Test. # # https://www.hackerrank.com/challenges/divisibility-of-power/problem # https://www.hackerrank.com/contests/infinitum-aug14/challenges/divisibility-of-power # challenge id: 2597 # import math # if x = ∏ pi^ei, find(i,j) | x <=> Ai^(...) | x <=> Ai^(...) = ∏ pi^(ei+...) # the worst case is x=2^54, Ai^(...) should equal to 2^(54+...) * ∏ pi^(...) # 2^53 < 10^16 < 2^54, 2^16 is the upper limit for x max_exp = math.ceil(math.log(10 ** 16) / math.log(2)) # 54 # modified but sufficient version of function find() def find(i, j, n): if n == 0: # stop the recursion return 0 # starting value 4 should be enough since 2^2^2 < 54 < 2^2^2^2 if i > j or A[i] == 1 or A[i + 1] == 0: return 1 # normal case, 1^n = 1, n^0 = 1 if A[i] == 0: return 0 # 0^n = 0 if A[i] >= max_exp: return max_exp # whatever A[i+1], if A[i]>=54 it's sufficient # the "real" function, value up to 54 return min(max_exp, A[i] ** find(i + 1, j, n - 1)) n = int(input()) A = list(map(int, input().strip().split())) A.append(0) # for testing A[i+1] without IndexError for _ in range(int(input())): i, j, x = map(int, input().strip().split()) i -= 1 # A[] is 0 based j -= 1 if x == 1 or i > j: a = 1 # trivial case else: a = pow(A[i], find(i + 1, j, 4), x) print('Yes' if a % x == 0 else 'No')
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Euler's Criterion # Detect whether the number is a quadratic residue. # # https://www.hackerrank.com/challenges/eulers-criterion/problem # def egcd(b, a): """ return a triple (g, x, y), such that ax + by = g = gcd(a, b) """ x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def mulinv(b, m): """ modular multiplicative inverse """ g, x, _ = egcd(b, m) if g == 1: return x % m def powmod(x, k, m): """ fast exponentiation x^k % m """ if k < 0: x = mulinv(x, m) k = -k p = 1 if k == 0: return p if k == 1: return x while k != 0: if k % 2 == 1: p = (p * x) % m x = (x * x) % m k //= 2 return p # Euler's Criterion -> Legendre symbol -> quadratic residue for _ in range(int(input())): A, M = map(int, input().split()) if A <= 1 or powmod(A, (M - 1) // 2, M) == 1: print('YES') else: print('NO')
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Dancing in Pairs # Find out if they can dance in pairs? # # https://www.hackerrank.com/challenges/dance-class/problem # https://www.hackerrank.com/contests/infinitum-jun14/challenges/dance-class # challenge id: 2561 # from decimal import Decimal for _ in range(int(input())): n = Decimal(input()) p = n.sqrt() print(["even", "odd"][int(p) % 2])
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Akhil and GF # Help Akhil in impressing his girlfriend # # https://www.hackerrank.com/challenges/akhil-and-gf/problem # https://www.hackerrank.com/contests/infinitum-aug14/challenges/akhil-and-gf # challenge id: 2324 # for _ in range(int(input())): n, m = map(int, input().split()) # 1111...11 = (10^n - 1) / 9 # 1111...11 mod m = ((10^n - 1) / 9) mod m # = ((10^n mod (m * 9)) - 1) / 9 p = pow(10, n, m * 9) print((p - 1) // 9)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Divisor Exploration II # Find the product of a sequence and then calculate the summation of its divisors. # # https://www.hackerrank.com/challenges/divisor-exploration-2/problem # https://www.hackerrank.com/contests/infinitum17/challenges/divisor-exploration-2 # challenge id: 12002 # # à exécuter en Pypy3, trop lent sinon... class Crible: """ Crible d'Eratosthène optimisé """ def __init__(self, n_max): self.n_max = n_max self.maximum = n = (n_max - 3) // 2 + 1 self.crible = crible = [False] * (n + 1) self._premiers = None self._phi = None i = 0 while i < n: while i < n: if not crible[i]: break i += 1 k = 3 while True: j = k * i + 3 * (k - 1) // 2 if j >= n: break crible[j] = True k += 2 i += 1 def liste(self): if self._premiers is None: premiers = [2] for i in range(1, self.maximum + 1): if not self.crible[i - 1]: premiers.append(2 * i + 1) self._premiers = premiers return self._premiers def egcd(b, a): """ algortihme d'Euclide étendu: (g, x, y) tel que ax + by = g = gcd(a, b) """ # https://fr.wikipedia.org/wiki/Algorithme_d%27Euclide_étendu x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def modinv(a, m): """ modular inverse avec Bachet-Bézout """ # https://fr.wikipedia.org/wiki/Théorème_de_Bachet-Bézout _, x, _ = egcd(a, m) return x % m # précalcul des 10^5 premiers nombres premiers crible = Crible(1299709 + 1) # le 100000e nombre premier primes = crible.liste() MOD = 1000000007 # la "vraie" formule, mais il faut calculer en arithmétique modulaire def sigma_1(p, a): return (pow(p, a + 1) - 1) // (p - 1) def F(p, a): return (p * sigma_1(p, a) - (a + 1)) // (p - 1) # numérateur et dénominateur de F() def F_num(p, a): return (pow(p, a + 2, MOD) - (p + (p - 1) * (a + 1)) % MOD) % MOD def F_den(p): return (p - 1) ** 2 def solve(m, a): n = d = 1 for i, p in enumerate(primes[:m], 1): n *= F_num(p, a + i) d *= F_den(p) n %= MOD d %= MOD r = n * modinv(d, MOD) r %= MOD print(r) for _ in range(int(input())): m, a = map(int, input().split()) solve(m, a)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Primitive Problem # Find the primitive roots of a prime number. # # https://www.hackerrank.com/challenges/primitive-problem/problem # https://www.hackerrank.com/contests/infinitum17/challenges/primitive-problem # # https://math.stackexchange.com/questions/124408/finding-a-primitive-root-of-a-prime-number def decompose(n): """ décomposition d'un nombre en facteurs premiers """ facteurs = {} i = 2 while i * i <= n: while n % i == 0: n = n // i facteurs[i] = facteurs.get(i, 0) + 1 if i >= 3: i += 2 else: i += 1 if n > 1: facteurs[n] = facteurs.get(n, 0) + 1 return facteurs def EulerPhi(n): """ calcul de l'Indicatrice d'Euler φ(n) ou totient(n) """ phi = n i = 2 while i * i <= n: if n % i == 0: phi -= phi // i while n % i == 0: n = n // i if i != 2: i += 2 else: i += 1 if n > 1: phi -= phi // n return phi def powmod(x, k, MOD): """ fast exponentiation x^k % MOD """ p = 1 if k == 0: return p if k == 1: return x while k != 0: if k % 2 == 1: p = (p * x) % MOD x = (x * x) % MOD k //= 2 return p def primitive_roots(p): s = EulerPhi(p) f = decompose(s) for a in range(2, p): ok = all(powmod(a, s // pi, p) != 1 for pi in f.keys()) if ok: break if len(decompose(p)) == 1: return a, EulerPhi(p - 1) # nota: ce cas n'arrive dans les testcases return a, "?" print(*primitive_roots(int(input())))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Identify Smith Numbers # Write a program to check whether a given integer is a Smith number. # # https://www.hackerrank.com/challenges/identify-smith-numbers/problem # def decompose(n): facteurs = [] i = 2 while i * i <= n: while n % i == 0: n = n // i facteurs.append(i) if i >= 3: i += 2 else: i += 1 if n > 1: facteurs.append(n) return facteurs N = input() # somme des chiffres des diviseurs sd = sum(sum(map(int, list(str(d)))) for d in decompose(int(N))) # somme des chiffres sc = sum(map(int, list(N))) print(int(sc == sd))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Easy GCD # Find the maximum number less than K such that GCD of all numbers is still more than one! # # https://www.hackerrank.com/challenges/easy-gcd-1/problem # import math import functools def gcd(*numbers): """ greatest common divisor """ return functools.reduce(math.gcd, numbers) def diviseur(n): """ premier diviseur premier de n """ i = 2 while i * i <= n: q, r = divmod(n, i) if r == 0: return i i += 1 return n n, k = map(int, input().split()) A = list(map(int, input().split())) g = gcd(*A) g = diviseur(g) print((k // g) * g)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Divisor Exploration 3 # Find the value given at the root of a tree constructing by the given rules. # # https://www.hackerrank.com/challenges/divisor-exploration-3/problem # https://www.hackerrank.com/contests/infinitum18/challenges/divisor-exploration-3 # challenge id: 12630 # MOD = 1000000007 # compute the 1000 first primes PRIME_1000 = 7919 # 7919 is the 1000th prime primes = [] sieve = [True] * (1 + PRIME_1000) for n in range(2, PRIME_1000 + 1): if sieve[n]: # by default, n is prime and add it to the list primes.append(n) # remove the multiples of n for i in range(n, PRIME_1000 + 1, n): sieve[i] = False def binomial(n, k): """ binomial coefficient """ if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 num = 1 den = 1 for i in range(1, min(k, n - k) + 1): # take advantage of symmetry num *= (n + 1 - i) den *= i c = num // den return c def f(i, p, a): # f(1,p,a) = p^a # f(i,p,a) = (p * f(i-1,p,a) - binomial(a+i-2,i-2)) / (p-1) for i >= 2 num = p ** a for j in range(2, i + 1): num = p * num - binomial(a + j - 2, j - 2) num //= p - 1 # print(" f({} {} {}) = {}".format(i, p, a, num)) return num % MOD def egcd(b, a): """ algortihme d'Euclide étendu: (g, x, y) tel que ax + by = g = gcd(a, b) """ # https://fr.wikipedia.org/wiki/Algorithme_d%27Euclide_étendu x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def modinv(a, m): """ modular inverse avec Bachet-Bézout """ # https://fr.wikipedia.org/wiki/Théorème_de_Bachet-Bézout g, x, _ = egcd(a, m) assert g == 1 return x % m def fast_f(i, p, a): # f(1,p,a) = p^a # f(i,p,a) = (p * f(i-1,p,a) - binomial(a+i-2,i-2)) / (p-1) for i >= 2 num, den = pow(p, a, MOD), 1 c_num, c_den = 1, 1 for j in range(2, i + 1): if j > 2: # compute the binomial coef c_num = (c_num * (a + j - 2)) % MOD c_den = (c_den * (j - 2)) % MOD num = (p * num * c_den - c_num * den) % MOD den = (den * (p - 1) * c_den) % MOD num = (num * modinv(den, MOD)) % MOD #print(" f({} {} {}) = {}".format(i, p, a, num)) return num def solve(m, a, d): # R = ∏ f(d,pᵢ,a+i) res = 1 for i in range(m): #x = f(d, primes[i], a + i + 1) % MOD x = fast_f(d, primes[i], a + i + 1) % MOD res *= x res %= MOD return res #assert solve(2,0,1) == 18 #assert solve(2,0,2) == 39 #assert solve(1,0,3) == 4 for _ in range(int(input())): m, a, d = map(int, input().split()) # 1 <= m, a, d <= 1000 print(solve(m, a, d))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Mathematics > Number Theory > Satisfactory Pairs // How many pairs of integers give a solution? // // https://www.hackerrank.com/challenges/pairs-again/problem // https://www.hackerrank.com/contests/w26/challenges/pairs-again // challenge id: 27017 // #include <bits/stdc++.h> using namespace std; int main() { vector<vector<unsigned>> divs; vector<bool> used; unsigned n; cin >> n; divs.resize(n + 1); used.resize(n + 1); // calcule les diviseurs de i ∈ [1, n] for (unsigned i = 1; i <= n; i++) { for (unsigned j = i; j <= n; j += i) { divs[j].push_back(i); } } unsigned nb = 0; for (unsigned a = 1; a <= n; a++) { for (unsigned x = 1; a * x <= n; x++) { for (unsigned d : divs[n - a * x]) { if (a < d) { if (!used[d]) { used[d] = true; nb++; } } } } for (unsigned x = 1; a * x <= n; x++) { for (unsigned d : divs[n - a * x]) { used[d] = false; } } } cout << nb << endl; return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
### [Mathematics](https://www.hackerrank.com/domains/mathematics) Without mathematics, there's nothing you can do. Everything around you is mathematics. Everything around you is numbers. #### [Number Theory](https://www.hackerrank.com/domains/mathematics/number-theory) Name | Preview | Code | Difficulty ---- | ------- | ---- | ---------- [Constructing a Number](https://www.hackerrank.com/challenges/constructing-a-number)|Construct a number divisible by 3 from the given numbers by reordering their digits.|[Python](constructing-a-number.py)|Easy [Closest Number](https://www.hackerrank.com/challenges/closest-number)|What is the closest number?|[Python](closest-number.py)|Medium [Sherlock and GCD](https://www.hackerrank.com/challenges/sherlock-and-gcd)|Help Sherlock in finding the subset.|[Python](sherlock-and-gcd.py)|Easy [Primitive Problem](https://www.hackerrank.com/challenges/primitive-problem)|Find the primitive roots of a prime number.|[Python](primitive-problem.py)|Easy [Identify Smith Numbers](https://www.hackerrank.com/challenges/identify-smith-numbers)|Write a program to check whether a given integer is a Smith number.|[Python](identify-smith-numbers.py)|Easy [Euler's Criterion](https://www.hackerrank.com/challenges/eulers-criterion)|Detect whether the number is a quadratic residue.|[Python](eulers-criterion.py)|Easy [Twins](https://www.hackerrank.com/challenges/twins)|How many pairs of twins can you find?|[Python](twins.py)|Medium [Fibonacci Finding (easy)](https://www.hackerrank.com/challenges/fibonacci-finding-easy)|Find some Fibonacci numbers!|[Python](fibonacci-finding-easy.py)|Easy [Little Panda Power](https://www.hackerrank.com/challenges/littlepandapower)|Compute A^B mod X|[Python](littlepandapower.py)|Hard [Mehta and his Laziness](https://www.hackerrank.com/challenges/mehta-and-his-laziness)|How will Mehta do these calculations?|[Python](mehta-and-his-laziness.py)|Hard [Minimal Distance to Pi](https://www.hackerrank.com/challenges/minimal-distance-to-pi)|Given a range of denominators, find the common fraction that best approximates Pi.|[Python](minimal-distance-to-pi.py)|Hard [Help Mike](https://www.hackerrank.com/challenges/help-mike)|Help Mike attend the NSA meeting|[Python](help-mike.py)|Hard [Dancing in Pairs](https://www.hackerrank.com/challenges/dance-class)|Find out if they can dance in pairs?|[Python](dance-class.py)|Hard [The Chosen One](https://www.hackerrank.com/challenges/the-chosen-one)|Given a list of integers, find and print an integer that is a divisor of all but one integer in the list.|[Python](the-chosen-one.py)|Medium [Power of large numbers](https://www.hackerrank.com/challenges/power-of-large-numbers)|How much does Hackerland coach pay to get Cristiano Ronaldo to play for his team?|[Python](power-of-large-numbers.py)|Medium [Salary Blues](https://www.hackerrank.com/challenges/salary-blues)|Help manager of HackerX company to normalize salaries.|[Python](salary-blues.py)|Medium [Akhil and GF](https://www.hackerrank.com/challenges/akhil-and-gf)|Help Akhil in impressing his girlfriend|[Python](akhil-and-gf.py)|Hard [Little Ashish's Huge Donation](https://www.hackerrank.com/challenges/little-chammys-huge-donation)|Help Ashish calculate donations.|[C++](little-chammys-huge-donation.cpp)|Hard [Manasa and Factorials](https://www.hackerrank.com/challenges/manasa-and-factorials)|Think about number of zeros in k!|[Python](manasa-and-factorials.py)|Hard [Number of zero-xor subsets](https://www.hackerrank.com/challenges/number-of-subsets)|How many subsets with zero xor are here?|[Python](number-of-subsets.py)|Medium [Breaking Sticks](https://www.hackerrank.com/challenges/breaking-sticks)|Find the length of the longest sequence of moves.|[C++](breaking-sticks.cpp)|Medium [Cheese and Random Toppings](https://www.hackerrank.com/challenges/cheese-and-random-toppings)|How many ways are there to choose exactly R toppings from N toppings?|[Python](cheese-and-random-toppings.py)|Easy [Easy GCD](https://www.hackerrank.com/challenges/easy-gcd-1)|Find the maximum number less than K such that GCD of all numbers is still more than one!|[Python](easy-gcd-1.py)|Medium [Satisfactory Pairs](https://www.hackerrank.com/challenges/pairs-again)|How many pairs of integers give a solution?|[C++](pairs-again.cpp)|Hard [Manasa loves Maths](https://www.hackerrank.com/challenges/manasa-loves-maths)|Find out if any permutation of the given number is divisible by 8.|[Python](manasa-loves-maths.py)|Medium [Largest Non-Coprime Submatrix](https://www.hackerrank.com/challenges/largest-coprime-submatrix)|Given a matrix find the largest coprime submatrix.|[C++](largest-coprime-submatrix.cpp)|Hard [John and GCD list](https://www.hackerrank.com/challenges/john-and-gcd-list)|Help John in making a list from GCD list|[Python](john-and-gcd-list.py)|Easy [Divisor Exploration II](https://www.hackerrank.com/challenges/divisor-exploration-2)|Find the product of a sequence and then calculate the summation of its divisors.|[Python](divisor-exploration-2.py)|Hard [Strange numbers](https://www.hackerrank.com/challenges/strange-numbers)|How many strange numbers belong to interval [L, R]?|[Python](strange-numbers.py)|Hard [Easy math](https://www.hackerrank.com/challenges/easy-math)|Help Johnny in figuring out the value of Y|[Python](easy-math.py)|Medium [Equations](https://www.hackerrank.com/challenges/equations)|Find the number of positive integral solutions for an equation.|[Python](equations.py)|Medium [Binomial Coefficients](https://www.hackerrank.com/challenges/binomial-coefficients)|Calculate how many binomial coefficients of n become 0 after modulo by P.|[Python](binomial-coefficients.py)|Medium [Lucy and Flowers](https://www.hackerrank.com/challenges/lucy-and-flowers)|Help Lucy's father with a computation involving flowers|[C++](lucy-and-flowers.cpp)|Medium [Divisor Exploration 3](https://www.hackerrank.com/challenges/divisor-exploration-3)|Find the value given at the root of a tree constructing by the given rules.|[C++](divisor-exploration-3.cpp) [Python](divisor-exploration-3.py)|Hard [Superpowers of 2](https://www.hackerrank.com/challenges/superpowers)|Just another numbers problem...|[Python](superpowers.py)|Advanced [Sherlock Puzzle](https://www.hackerrank.com/challenges/sherlock-puzzle)|Help Sherlock get close to his Arch Nemesis, Jim Moriarty.|[Python](sherlock-puzzle.py)|Hard [Divisibility of Power](https://www.hackerrank.com/challenges/divisibility-of-power)|Divisibility Test.|[Python](divisibility-of-power.py)|Medium [Devu Vs Police](https://www.hackerrank.com/challenges/devu-police)|Help Devu escape from police|[Python](devu-police.py)|Hard [Long Permutation](https://www.hackerrank.com/challenges/long-permutation)|Determine the n^th element of an infinite permutation!|[Python](long-permutation.py)|Hard [Megaprime Numbers](https://www.hackerrank.com/challenges/megaprime-numbers)|Count the number of primes in a given range that consist only of prime digits.|[Python](megaprime-numbers.py)|Medium [Divisor Exploration](https://www.hackerrank.com/challenges/divisor-exploration)|Find and print the number of divisors for each dataset.|[Python](divisor-exploration.py)|Hard [Prime Sum](https://www.hackerrank.com/challenges/prime-sum)|Represent a number as sum of primes.|[Python](prime-sum.py)|Medium [nCr](https://www.hackerrank.com/challenges/ncr)|Given n and r, in how many ways can r items be chosen from n items?|[Python](ncr.py)|Expert [Fibonacci GCD](https://www.hackerrank.com/challenges/fibonacci-gcd)|Find gcd for n fibonacci numbers.|[Python](fibonacci-gcd.py)|Hard
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > Binomial Coefficients # Calculate how many binomial coefficients of n become 0 after modulo by P. # # https://www.hackerrank.com/challenges/binomial-coefficients/problem # challenge id: 107 # # corollaire du théorème de Lucas https://en.wikipedia.org/wiki/Lucas%27s_theorem def solve(n, p): a = 1 n1 = n + 1 while n >= p: n, r = divmod(n, p) a *= r + 1 a *= n + 1 a = n1 - a print(a) for _ in range(int(input())): n, p = map(int, input().split()) solve(n, p)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Number Theory > nCr # Given n and r, in how many ways can r items be chosen from n items? # # https://www.hackerrank.com/challenges/ncr/problem # challenge id: 115 # from math import factorial MAX = 38 C = [[0 for _ in range(MAX) ] for _ in range(MAX)] # Calculate value of Binomial Coefficient in bottom up manner # https://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/ for i in range(MAX): for j in range(i + 1): # Base Cases if j == 0 or j == i: C[i][j] = 1 # Calculate value using previously stored values else: C[i][j] = C[i-1][j-1] + C[i-1][j] def nCr(n, r): """ binomial coefficient: n choose r """ if n < r: return 0 return factorial(n) // factorial(r) // factorial(n - r) def lucas(n, r, p): """ Théorème de Lucas """ # https://fr.wikipedia.org/wiki/Théorème_de_Lucas assert n >= r c = 1 while r != 0: c = (c * C[n % p][r % p]) % p n //= p r //= p return c def egcd(b, a): """ algortihme d'Euclide étendu: (g, x, y) tel que ax + by = g = gcd(a, b) """ # https://fr.wikipedia.org/wiki/Algorithme_d%27Euclide_étendu x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def modinv(a, m): """ modular inverse avec Bachet-Bézout """ # https://fr.wikipedia.org/wiki/Théorème_de_Bachet-Bézout g, x, _ = egcd(a, m) assert g == 1 return x % m """ autre possibilité: def modinv(a, m): # https://fr.wikipedia.org/wiki/Théorème_d%27Euler_(arithmétique) # a et m coprime phi = {27: 18, 11: 10, 13: 12, 37: 36} return pow(a, phi[m] - 1, m) """ def crt(a, n): """ Théorème des restes chinois """ # https://fr.wikipedia.org/wiki/Théorème_des_restes_chinois p = 1 for i in n: p *= i r = 0 for ai, ni in zip(a, n): r += ai * (p // ni) * modinv(p // ni, ni) return r % p def v(n, p): """ formule de Legendre: exposant de p dans n! """ # https://fr.wikipedia.org/wiki/Formule_de_Legendre s = 0 while n != 0: n //= p s += n return s fa = [1] * 28 for i in range(28): fa[i] = (fa[i - 1] * (i if i % 3 != 0 else 1)) % 27 def f_mod27(n): return (pow(fa[27], n // 27, 27) * fa[n % 27]) % 27 def fact_mod27(n): i = 1 ret = 1 while i <= n: ret = (ret * f_mod27(n // i)) % 27 i *= 3 return ret def nCr_mod27(n, r): """ (n r) mod 27 """ # (n r) = n! / r! / (n-r)! # x! mod 27 = F(x) * 3^v(x,3) mod 27 e = (v(n, 3) - v(r, 3) - v(n - r, 3)) return (3 ** e * fact_mod27(n) * modinv(fact_mod27(r) * fact_mod27(n - r), 27)) % 27 def solve(n, r): # 142857 = 3 * 3 * 3 * 11 * 13 * 37 a = [nCr_mod27(n, r), lucas(n, r, 11), lucas(n, r, 13), lucas(n, r, 37)] p = [27, 11, 13, 37] print(crt(a, p)) for _ in range(int(input())): n, r = map(int, input().split()) solve(n, r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Diwali Lights # Number of ways to light the room # # https://www.hackerrank.com/challenges/diwali-lights/problem # # chaque lampe peut être allumée ou éteinte # il y a donc 2^n possibilités pour n lampes # -1 parce qu'il en faut une allumé for n in range(int(input())): n = int(input()) print((2 ** n - 1) % 100000)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
""" Sherlock and Permutations https://www.hackerrank.com/challenges/sherlock-and-permutations """ import sys from math import factorial def C(n, k): return factorial(n) // factorial(k) // factorial(n - k) def solve(m0, m1): m1 -= 1 if m0 == 0 or m1 == 0: print(1) else: print(C(m0 + m1, m0) % 1000000007) if len(sys.argv) == 3: solve(int(sys.argv[1]), int(sys.argv[2])) else: nb = int(input()) for _ in range(nb): m0, m1 = map(int, input().split()) solve(m0, m1)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Russian Peasant Exponentiation # The only correct way to raise numbers in powers. # # https://www.hackerrank.com/challenges/russian-peasant-exponentiation/problem # for _ in range(int(input())): a, b, k, m = map(int, input().split()) # calcule (a + b∙𝑖)^k mod m if k == 0: print(1, 0) else: while k % 2 == 0: # (a + b∙𝑖)² = a² + 2a∙b∙𝑖 - b² a, b = a * a - b * b, 2 * a * b a, b = a % m, b % m k //= 2 c, d = a, b k //= 2 while k > 0: a, b = a * a - b * b, 2 * a * b a, b = a % m, b % m if k % 2 == 1: # (a + b∙𝑖)×(c + d∙𝑖) c, d = a * c - b * d, d * a + c * b c, d = c % m, d % m k //= 2 print(c, d)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Sumar and the Floating Rocks # Count the number of integral rocks between Harry and Hermoine # # https://www.hackerrank.com/challenges/harry-potter-and-the-floating-rocks/problem # from math import gcd for _ in range(int(input())): x1, y1, x2, y2 = map(int, input().split()) # y = A* x + B # y1 = A * x1 + B # y2 = A * x2 + B # A = (y2-y1) / (x2-x1) f = gcd(y2 - y1, x2 - x1) - 1 print(f)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Fundamentals > Halloween party # Help Alex give Silvia the maximum number of chocolates # # https://www.hackerrank.com/challenges/halloween-party/problem # for _ in range(int(input())): K = int(input()) # K pair: on coupe K/2 fois horizontalement et K/2 fois verticalement # K impair: on coupe une fois de plus horizontalement ou verticalement print((K // 2) * ((K + 1) // 2))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
// Special Multiple // Can you find the least positive integer that is made of only 0s and 9s? - 30 Points // // https://www.hackerrank.com/challenges/special-multiple/problem // // cf. special-multiple.py pour l'explication #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> long nine_zero(int n) { for (int i = 1; ; ++i) { long multiple = 0; long chiffre = 9; for (int j = i; j != 0; j = j >> 1) { if (j & 1) multiple += chiffre; chiffre *= 10; } if (multiple % n == 0) return multiple; } } int main() { int t, n; scanf("%d", &t); while (t--) { scanf("%d", &n); printf("%ld\n", nine_zero(n)); } return 0; }
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Army Game # Find the minimum number of supply packages Luke must drop to supply all of his army bases. # # https://www.hackerrank.com/challenges/game-with-cells/problem # n, m = map(int, input().split()) r = ((n + 1) // 2) * ((m + 1) // 2) print(r)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Special Multiple # Can you find the least positive integer that is made of only 0s and 9s? - 30 Points # # https://www.hackerrank.com/challenges/special-multiple/problem # # Le plus simple est décrire 1, 2, 3... en "binaire" {0,9} (au lieu de {0,1}) # et tester la divisibilité du nombre trouvé # Amusant :) L'éditorial donne la même solution élégante en Python # tandis que le tester code est carrément plus obscur def nine_zero(n): for i in range(1, 100000): f = int(bin(i)[2:]) * 9 if f % n == 0: return f return "?" for n in range(int(input())): print(nine_zero(int(input())))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Fundamentals > Jim and the Jokes # Jim is running out of jokes! Help him finding new jokes. # # https://www.hackerrank.com/challenges/jim-and-the-jokes/problem # # algo: créer une table qui compte les nombres lus dans la base indiquée jokes = {} for _ in range(int(input())): b, x = input().split() try: f = int(x, int(b)) jokes[f] = jokes.get(f, 0) + 1 except ValueError: # erreur de conversion dans la base donnée pass # attention: quand il y a plusieurs fois le même nombre, toutes les valeurs comptent print(sum(f * (f - 1) // 2 for f in jokes.values() if f >= 1))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Fundamentals > Is Fibo # Find out if a number is a Fibonacci Number or not. # # https://www.hackerrank.com/challenges/is-fibo/problem # import bisect SOLUTION = 4 fibo_max = 10 ** 10 fibo = [0, 1, 2] while True: c = fibo[-2] + fibo[-1] if c > fibo_max: break fibo.append(c) if SOLUTION == 0: # recherche basique dans le tableau de 50 éléments def is_fibo(n): return n in fibo elif SOLUTION == 1: fibonacci = {} for i in fibo: fibonacci[i] = True # recherche par hash def is_fibo(n): return n in fibonacci elif SOLUTION == 2: # binary search, fibo[] est déjà trié def is_fibo(n): i = bisect.bisect_right(fibo, n) return i > 0 and fibo[i - 1] == n elif SOLUTION == 3: n_fibo = len(fibo) # autre dichotomie def is_fibo(n): i = bisect.bisect_left(fibo, n) return i < n_fibo and fibo[i] == n elif SOLUTION == 4: n_fibo = len(fibo) # dichotomie manuelle def is_fibo(n): lo, hi = 0, n_fibo while lo < hi: mid = (lo + hi) // 2 if fibo[mid] < n: lo = mid + 1 elif fibo[mid] == n: return True else: hi = mid return False for _ in range(int(input())): print("IsFibo" if is_fibo(int(input())) else "IsNotFibo")
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Summing the N series # Sum the N series. # # https://www.hackerrank.com/challenges/summing-the-n-series/problem # # c'est quand même plus facile que les problèmes de Project Euler... for _ in range(int(input())): n = int(input()) print((n ** 2) % 1000000007)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Handshake # Count the number of Handshakes in a board meeting. # # https://www.hackerrank.com/challenges/handshake/problem # T = int(input()) for a0 in range(T): N = int(input()) print(N * (N - 1) // 2)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Most Distant # Measure the gap between the two most distant coordinates. # # https://www.hackerrank.com/challenges/most-distant/problem # # la plus grande distance se situe forcément entre deux extrêmités # du quadrilatère entourant les points n = int(input()) x, y = map(float, input().split()) x0, y0, x1, y1 = x, y, x, y for _ in range(1, n): x, y = map(int, input().split()) x0 = min(x0, x) x1 = max(x1, x) y0 = min(y0, y) y1 = max(y1, y) print("{:6f}".format(max(x1 - x0, y1 - y0, (x0 ** 2 + y1 ** 2) ** 0.5, (x0 ** 2 + y0 ** 2) ** 0.5, (x1 ** 2 + y1 ** 2) ** 0.5, (x1 ** 2 + y0 ** 2) ** 0.5)))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Sherlock and Divisors # Help Sherlock in Counting Divisors. # # https://www.hackerrank.com/challenges/sherlock-and-divisors/problem # # from my eulerlib.py def diviseurs(n): div = [1] i = 2 while i * i <= n: q, r = divmod(n, i) if r == 0: div.append(i) if i != q: div.append(q) i += 1 if n != 1: div.append(n) return div def even_divisors(n): return sum(1 for d in diviseurs(n) if d % 2 == 0) if __name__ == '__main__': for _ in range(int(input())): n = int(input()) result = even_divisors(n) print(result)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Minimum Height Triangle # Find the smallest height of a triangle preserving the given constraints. # # https://www.hackerrank.com/challenges/lowest-triangle/problem # base, area = map(int, input().split()) height = (2 * area - 1) // base + 1 print(height)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Fundamentals > Mutual Recurrences # Compute terms in a mutual recurrence. # # https://www.hackerrank.com/challenges/mutual-recurrences/problem # https://www.hackerrank.com/contests/infinitum14/challenges/mutual-recurrences # challenge id: 15898 # import sys MOD = 1000000000 #------------------------------------------------------------------------------ a, b, c, d, e, f, g, h = 0, 0, 0, 0, 0, 0, 0, 0 cache_x = None cache_y = None def x(n): if n < 0: return 1 v = cache_x[n] if v == 0: v = x(n - a) + y(n - b) + y(n - c) + n * d ** n cache_x[n] = v return v def y(n): if n < 0: return 1 v = cache_y[n] if v == 0: v = y(n - e) + x(n - f) + x(n - g) + n * h ** n cache_y[n] = v return v #------------------------------------------------------------------------------ class Matrice: def __init__(self, n, v=None): self.n = n self.v = [0] * (n * n) if v is not None: if isinstance(v, int) and v == 1: for i in range(n): self.v[i + n * i] = 1 elif isinstance(v, list) and len(v) == n * n: self.v = v else: raise ValueError def __setitem__(self, xy, v): self.v[xy[0] + self.n * xy[1]] = v def __getitem__(self, xy): return self.v[xy[0] + self.n * xy[1]] def __call__(self, x, y): return self.v[x + self.n * y] def __str__(self): n = self.n m = [max(len(str(self.v[x + n * y])) for y in range(n)) for x in range(n)] s = '' for i in range(0, n * n, n): s += '[' if i == 0 else ' ' s += ' '.join(str(self.v[j]).rjust(m[j - i]) for j in range(i, i + n)) s += ']' if i == n * n - n else '\n' return s def __imod__(self, m): """ A %= m """ for i in range(self.n * self.n): self.v[i] %= m return self def tr(self): n = self.n Ap = Matrice(n) for x in range(n): for y in range(n): Ap.v[x + n * y] = self.v[y + n * x] return Ap class Vecteur: def __init__(self, n, v=None): self.n = n self.v = [0] * n if v is not None: if isinstance(v, list) and len(v) == n: self.v = v else: raise ValueError def __setitem__(self, x, v): self.v[x] = v def __getitem__(self, x): return self.v[x] def __call__(self, x): return self.v[x] def __str__(self): n = self.n s = '[' + ' '.join(map(str, self.v)) + ']' return s def __imod__(self, m): """ V %= m """ for i in range(self.n): self.v[i] %= m return self def multm(A, B): """ produit matriciel: A * B """ assert A.n == B.n n = A.n r = Matrice(n) for x in range(n): for y in range(n): r[(x, y)] = sum(A(i, y) * B(x, i) for i in range(n)) % MOD return r def multv(A, V): """ produit matrice/vecteur: A * V """ assert A.n == V.n n = A.n r = Vecteur(n) for y in range(n): r[y] = sum(A(i, y) * V(i) for i in range(n)) % MOD return r def power(M, k): """ fast exponentiation M^k """ P = Matrice(M.n, 1) if k == 0: return P if k == 1: return M while k != 0: if k % 2 == 1: P = multm(P, M) M = multm(M, M) k //= 2 return P #------------------------------------------------------------------------------ def fibonacci_easy(a, b, n): A = Matrice(2, [1, 1, 1, 0]) An = power(A, n) F0 = Vecteur(2, [b, a]) Fn = multv(An, F0) print(Fn[1]) def solve(a, b, c, d, e, f, g, h, n): A = Matrice(24) A[( a - 1, 0)] += 1 # x(n) = x(n - a) A[(10 + b - 1, 0)] += 1 # + y(n - b) A[(10 + c - 1, 0)] += 1 # + y(n - c) A[( 22, 0)] += 1 # + n * d ** n A[(10 + e - 1, 10)] += 1 # y(n) = y(n - e) A[( f - 1, 10)] += 1 # + x(n - f) A[( g - 1, 10)] += 1 # + x(n - g) A[( 20, 10)] += 1 # + n * h ** n for i in range(1, 10): A[(i - 1, i)] += 1 A[(10 + i - 1, 10 + i)] += 1 A[(20, 20)] = h A[(21, 20)] = h A[(21, 21)] = h A[(22, 22)] = d A[(23, 22)] = d A[(23, 23)] = d V = Vecteur(24, [1] * 24) V[20] = 0 V[22] = 0 # print(A, file=sys.stderr) A = power(A, n + 1) r = multv(A, V) print(r[0], r[10]) if __name__ == '__main__': for _ in range(int(input())): a, b, c, d, e, f, g, h, n = map(int, input().split()) """ naif cache_x = [0] * (n + 1) cache_y = [0] * (n + 1) print(x(n) % MOD, y(n) % MOD) """ solve(a, b, c, d, e, f, g, h, n)
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }
# Mathematics > Fundamentals > Bus Station # Find all suitable bus sizes # # https://www.hackerrank.com/challenges/bus-station/problem # #TODO import sys n = int(input()) a = list(map(int, input().split())) result = [] # solution timeout if False: max = sum(a) bus = 1 while bus <= max: if max % bus != 0: bus += 1 continue x = bus i = 0 while i < n: x -= a[i] if x < 0: break if x == 0: x = bus i += 1 if i == n and x == bus: # sys.stdout.write(str(bus) + " ") result.append(str(bus)) bus += 1 # solution OK # on considère la taille du bus R comme le cumul des groupes qui restent # et on vérifie que les groupes précédents sont compatibles # |------------------------------------| # <----- L -----><-------- R --------> # à chaque instant, on doit avoir les groupes du côté L qui tiennent # parfaitement dans un bus de taille R if True: L = 0 R = sum(a) for x in a: if R == 0: break if L % R == 0: bus = 0 for i in a: bus += i if bus == R: bus = 0 elif bus > R: break if bus == 0: result.insert(0, str(R)) L += x R -= x print(" ".join(result))
{ "repo_name": "rene-d/hackerrank", "stars": "65", "repo_language": "Python", "file_name": "README.md", "mime_type": "text/plain" }