I have a homework question I've been having trouble with.
I have to write a function that checks if every alternate digit in a given number has the same parity. For example, both 1 2 3 3 and 2 1 3 3 are valid, but 1324 is not. I have no idea how to go about doing this, though. How do I keep track of previous digits, for one thing? Any help would be much appreciated.
Edit: My efforts so far:
Any number < 100 clearly isn't acceptable (right?) since 'every alternate digit' doesn't really make sense here. For 3-digit numbers, this should work:
function validate(n) {
var i, copy, l = [0, 0];
if (isNaN(n) || (n < 100)) {
return false;
} else {
copy = Math.round(n);
for (i = copy.toString().length; i--; n = Math.floor(n / 10)) {
l[0] = l[1];
l[1] = l[2];
l[2] = n % 10;
}
if ((l[0] % 2) == (l[2] % 2)) return true;
}
}
Edit[2]: Thanks for your help, everybody. I've managed to get an honest-to-goodness real (I think) working function based on Salix alba's first suggestion to save the parities of the first and second digits. The loops run backward over the digits.
For now, this (along with making a couple of minor edits to save the parities of the last and second-last digits instead as Salix alba said, which would make the parity = lines simpler) is my solution:
function validate(n) {
var copy, len, parity, broke = 0, i = 2;
if (!isNaN(n) || (n >= 100)) {
n = Math.round(n);
len = n.toString().length;
copy = n; // save
parity = Math.floor(n / Math.pow(10, len - 1)) % 2;
n = Math.floor(n / 10);
while (i < len) {
if (parity != ((n % 10) % 2)) {
broke++;
break;
}
i += 2;
n = Math.floor(n / 100);
}
n = copy; // restore
i = 1;
parity = (Math.floor(n / Math.pow(10, len - 2)) % 10) % 2;
while (i < len) {
if (parity != ((n % 10) % 2)) {
broke++;
break;
}
i += 2;
n = Math.floor(n / 100);
}
if (broke != 2) return true;
}
return false;
}
It's a horrible mess, of course. I would really, really appreciate any ideas for make this more efficient, easier to read, etc.
(Also going to try to write another function with jing3142's method of iterating with a flag, which might make the loops simpler.)
You are working along the right lines but there are a number of issues. You code only works for three digits since your check if ((l[0] % 2) == (l[2] % 2)) return true; only operates once at the end of the loop.
So you need to set a flag, say valid and put valid = valid && ((l[0] % 2) == (l[2] % 2)) inside the loop.
The loop will now fail because the first use of l[2] in l[1] = l[2] will be undefined since it has not been defined.
If you correct these then you will need to check whether there are an even or odd number of digits else it will fail for an odd number of digits.
Also you imply in your comment that you are not to use strings and in practice you do even if it is only to find the length.
There is another way.
The clues in your working out is that if n<100 then no check can be done, and that you need to reduce n be a factor of 10 each time through n = Math.floor(n / 10) while you loop.
Rather than give you a solution as you ask for advice not a solution here is a hint.
given that n>100 to start with and if U is unit digit, T tens digit and H hundreds digit of n then while n>100 how do you calculate U and H, how do you then set the valid flag, in the loop?
EDIT Looks like you still need some help
Algorithm not code
function validate(n) {
if(n<100) return not applicable
valid=true
while(n>100) {
U=n % 10
H=Floor(n /100) % 10
valid = valid && ((U % 2) == (H % 2))
n=Floor(n/10)
}
return valid
}
Related
I'm having performance issues when trying to check whether integer n is a perfect square (sqrt is a whole number) when using BigInt. Using normal numbers below Number.MAX_SAFE_INTEGER gives reasonable performance, but attempting to use BigInt even with the same number range causes a huge performance hit.
The program solves the Battle of Hastings perfect square riddle put forth by Sam Loyd whereby my program iterates over the set of real numbers n (in this example, up to 7,000,000) to find instances where variable y is a whole number (perfect square). I'm interested in the original square root of one of the 13 perfect squares where this condition is satisfied, which is what my code generates (there's more than one).
Assuming y^2 < Number.MAX_SAFE_INTEGER which is 2^53 – 1, this can be done without BigInt and runs in ~60ms on my machine:
const limit = 7_000_000;
var a = [];
console.time('regular int');
for (let n = 1; n < limit; n++) {
if (Math.sqrt(Math.pow(n, 2) * 13 + 1) % 1 === 0)
a.push(n);
}
console.log(a.join(', '));
console.timeEnd('regular int');
Being able to use BigInt would mean I could test for numbers much higher than the inherent number variable limit 2^53 - 1, but BigInt seems inherently slower; unusably so. To test whether a BigInt is a perfect square, I have to use a third party library as Math.sqrt doesn't exist for BigInt such that I can check if the root is perfect, as all sqrt returns a floor value. I adapted functions for this from a NodeJS library, bigint-isqrt and bigint-is-perfect-square.
Thus, using BigInt with the same limit of 7,000,000 runs 35x slower:
var integerSQRT = function(value) {
if (value < 2n)
return value;
if (value < 16n)
return BigInt(Math.sqrt(Number(value)) | 0);
let x0, x1;
if (value < 4503599627370496n)
x1 = BigInt(Math.sqrt(Number(value))|0) - 3n;
else {
let vlen = value.toString().length;
if (!(vlen & 1))
x1 = 10n ** (BigInt(vlen / 2));
else
x1 = 4n * 10n ** (BigInt((vlen / 2) | 0));
}
do {
x0 = x1;
x1 = ((value / x0) + x0) >> 1n;
} while ((x0 !== x1 && x0 !== (x1 - 1n)));
return x0;
}
function perfectSquare(n) {
// Divide n by 4 while divisible
while ((n & 3n) === 0n && n !== 0n) {
n >>= 2n;
}
// So, for now n is not divisible by 2
// The only possible residual modulo 8 for such n is 1
if ((n & 7n) !== 1n)
return false;
return n === integerSQRT(n) ** 2n;
}
const limit = 7_000_000;
var a = [];
console.time('big int');
for (let n = 1n; n < limit; n++) {
if (perfectSquare(((n ** 2n) * 13n) + 1n))
a.push(n);
}
console.log(a.join(', '));
console.timeEnd('big int');
Ideally I'm interested in doing this with a much higher limit than 7 million, but I'm unsure whether I can optimise the BigInt version any further. Any suggestions?
You may be pleased to learn that some recent improvements on V8 have sped up the BigInt version quite a bit; with a recent V8 build I'm seeing your BigInt version being about 12x slower than the Number version.
A remaining challenge is that implementations of BigInt-sqrt are typically based on Newton iteration and hence need an estimate for a starting value, which should be near the final result, so about half as wide as the input, which is given by log2(X) or bitLength(X). Until this proposal gets anywhere, that can best be done by converting the BigInt to a string and taking that string's length, which is fairly expensive.
To get faster right now, #Ouroborus' idea is great. I was curious how fast it would be, so I implemented it:
(function betterAlgorithm() {
const limit = 7_000_000n;
var a = [];
console.time('better algorithm');
let m = 1n;
let m_squared = 1n;
for (let n = 1n; n < limit; n += 1n) {
let y_squared = n * n * 13n + 1n;
while (y_squared > m_squared) {
m += 1n;
m_squared = m * m;
}
if (y_squared === m_squared) {
a.push(n);
}
}
console.log(a.join(', '));
console.timeEnd('better algorithm');
})();
As a particular short-term detail, this uses += 1n instead of ++, because as of today, V8 hasn't yet gotten around to optimizing ++ for BigInts. This difference should disappear eventually (hopefully soon).
On my machine, this version takes only about 4x as much time as your original Number-based implementation.
For larger numbers, I would expect some gains from replacing the multiplications with additions (based on the observation that the delta between consecutive square numbers grows linearly), but for small-ish upper limits that appears to be a bit slower. If you want to toy around with it, this snippet describes the idea:
let m_squared = 1n; // == 1*1
let m_squared_delta = 3n; // == 2*2 - 1*1
let y_squared = 14n; // == 1*1*13+1
let y_squared_delta = 39n; // == 2*2*13+1 - 1*1*13+1
for (let n = 1; n < limit; n++) {
while (y_squared > m_squared) {
m_squared += m_squared_delta;
m_squared_delta += 2n;
}
if (y_squared === m_squared) {
a.push(n);
}
y_squared += y_squared_delta;
y_squared_delta += 26n;
}
The earliest where this could possibly pay off is when the results exceed 2n**64n; I wouldn't be surprised if it wasn't measurable before 2n**256n or so.
The problem is: Print out how much odd numbers there are in a given number.
function oddCount(n) {
var odd = [];
for (i = 0; i < n; i++) {
if (i % 2 == 1) {
odd.push([i]);
}
}
return odd.length;
}
console.log(oddCount(8));
As we can see, it works properly, however, on codewars, it wants me to optimize it to run faster. Can someone show me how so I can learn it quickly please.
function oddCount(n) {
var odd = [];
for (i = 0; i < n; i++) {
if (i & 0x1 == 1) {
odd.push([i]);
}
}
return odd.length;
}
console.log(oddCount(8));
or
function oddCount(n) {
return (n - (n & 0x01)) / 2;
}
console.log(oddCount(8));
Neither "ceil" or "floor" is a correct answer as a one liner. "ceil" will make the division Base 1, "floor" will make the division Base 0. So both could be used in an implementation, but the "polarity" of n matters.
It's necessary to check whether the input number is odd or even.
function oddCount(n) {
// odd / even check
if (n % 2 == 0) {
// its even, we can divide by 2
return n / 2
}
else {
// n is odd, so we must include n as a count+1 itself
return ((n - 1) / 2) + 1
}
}
// Disclaimer: Are negative numbers odd or even? In this code they
// apparently aren't handled. So the set of numbers are integers from
// 0 to +Infinity
// Test cases:
console.log( oddCount(8) ); // 4
console.log( oddCount(9) ); // 5
But this code "breaks" if n itself is 0 or less. So we need to fix it:
Right after we say function oddCount(n) {, put:
if (n < 1) return 0;
All worries solved. But still debate on whether 0 is odd or even, and whether -1 is odd and -2 is even.
I believe this should work.
function oddCount(n) {
return Math.ceil(n/2);
}
console.log(oddCount(8));
If the number is an even number, there's n/2 odd numbers
Eg if n is 6
*1*,2,*3*,4,*5*,6
If it is an odd number, there's n/2+1 odd numbers. Because n-1 would be even
Eg if n is 5
*1*,2,*3*,4, + *5*
So basically
if (n%2==0) return n/2
else return (n-1)/2+1
The for loops aren't needed
Also like the others pointed out, ceiling is a more concise way to do it
return Math.ceil(n/2)
I'm trying to solve all the lessons on codility but I failed to do so on the following problem: Ladder by codility
I've searched all over the internet and I'm not finding a answer that satisfies me because no one answers why the max variable impacts so much the result.
So, before posting the code, I'll explain the thinking.
By looking at it I didn't need much time to understand that the total number of combinations it's a Fibonacci number, and removing the 0 from the Fibonacci array, I'd find the answer really fast.
Now, afterwards, they told that we should return the number of combinations modulus 2^B[i].
So far so good, and I decided to submit it without the var max, then I got a score of 37%.. I searched all over the internet and the 100% result was similar to mine but they added that max = Math.pow(2,30).
Can anyone explain to me how and why that max influences so much the score?
My Code:
// Powers 2 to num
function pow(num){
return Math.pow(2,num);
}
// Returns a array with all fibonacci numbers except for 0
function fibArray(num){
// const max = pow(30); -> Adding this max to the fibonaccy array makes the answer be 100%
const arr = [0,1,1];
let current = 2;
while(current<=num){
current++;
// next = arr[current-1]+arr[current-2] % max;
next = arr[current-1]+arr[current-2]; // Without this max it's 30 %
arr.push(next);
}
arr.shift(); // remove 0
return arr;
}
function solution(A, B) {
let f = fibArray(A.length + 1);
let res = new Array(A.length);
for (let i = 0; i < A.length; ++i) {
res[i] = f[A[i]] % (pow(B[i]));
}
return res;
}
console.log(solution([4,4,5,5,1],[3,2,4,3,1])); //5,1,8,0,1
// Note that the console.log wont differ in this solution having max set or not.
// Running the exercise on Codility shows the full log with all details
// of where it passed and where it failed.
The limits for input parameters are:
Assume that:
L is an integer within the range [1..50,000];
each element of array A is an integer within the range [1..L];
each element of array B is an integer within the range [1..30].
So the array f in fibArray can be 50,001 long.
Fibonacci numbers grow exponentially; according to this page, the 50,000th Fib number has over 10,000 digits.
Javascript does not have built-in support for arbitrary precision integers, and even doubles only offer ~14 s.f. of precision. So with your modified code, you will get "garbage" values for any significant value of L. This is why you only got 30%.
But why is max necessary? Modulo math tells us that:
(a + b) % c = ([a % c] + [b % c]) % c
So by applying % max to the iterative calculation step arr[current-1] + arr[current-2], every element in fibArray becomes its corresponding Fib number mod max, without any variable exceeding the value of max (or built-in integer types) at any time:
fibArray[2] = (fibArray[1] + fibArray[0]) % max = (F1 + F0) % max = F2 % max
fibArray[3] = (F2 % max + F1) % max = (F2 + F1) % max = F3 % max
fibArray[4] = (F3 % max + F2 % max) = (F3 + F2) % max = F4 % max
and so on ...
(Fn is the n-th Fib number)
Note that as B[i] will never exceed 30, pow(2, B[i]) <= max; therefore, since max is always divisible by pow(2, B[i]), applying % max does not affect the final result.
Here is a python 100% answer that I hope offers an explanation :-)
In a nutshell; modulus % is similar to 'bitwise and' & for certain numbers.
eg any number % 10 is equivalent to the right most digit.
284%10 = 4
1994%10 = 4
FACTS OF LIFE:
for multiples of 2 -> X % Y is equivalent to X & ( Y - 1 )
precomputing (2**i)-1 for i in range(1, 31) is faster than computing everything in B when super large arrays are given as args for this particular lesson.
Thus fib(A[i]) & pb[B[i]] will be faster to compute than an X % Y style thingy.
https://app.codility.com/demo/results/trainingEXWWGY-UUR/
And for completeness the code is here.
https://github.com/niall-oc/things/blob/master/codility/ladder.py
Here is my explanation and solution in C++:
Compute the first L fibonacci numbers. Each calculation needs modulo 2^30 because the 50000th fibonacci number cannot be stored even in long double, it is so big. Since INT_MAX is 2^31, the summary of previously modulo'd numbers by 2^30 cannot exceed that. Therefore, we do not need to have bigger store and/or casting.
Go through the arrays executing the lookup and modulos. We can be sure this gives the correct result since modulo 2^30 does not take any information away. E.g. modulo 100 does not take away any information for subsequent modulo 10.
vector<int> solution(vector<int> &A, vector<int> &B)
{
const int L = A.size();
vector<int> fibonacci_numbers(L, 1);
fibonacci_numbers[1] = 2;
static const int pow_2_30 = pow(2, 30);
for (int i = 2; i < L; ++i) {
fibonacci_numbers[i] = (fibonacci_numbers[i - 1] + fibonacci_numbers[i - 2]) % pow_2_30;
}
vector<int> consecutive_answers(L, 0);
for (int i = 0; i < L; ++i) {
consecutive_answers[i] = fibonacci_numbers[A[i] - 1] % static_cast<int>(pow(2, B[i]));
}
return consecutive_answers;
}
goal: take a number like 54321, add the numbers together (5+4+3+2+1 = 15), then take that number (15) add the digits (1+5 = 6), so return 6;
here is my code:
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
}
}
digital_root(1632)
Can't figure out: How to get that function to repeat over and over until digits is just one number (i.e. less than 10). I have tried a variety of nested functions, but can't seem to get it right.
If possible please point me in the direction to the solution ("try a nesting in a while... or read up on..."), but don't give me the complete code solution ("Use this code chunk:...."). I've developed a bad habit of just reading and copying...
Thank you!
Try this: reference HERE
function digital_root(n) {
var singlesum = 0;
while (n >= 10 ) {
singlesum=0;
while (n > 0) {
var rem;
rem = n % 10;
singlesum = singlesum + rem;
n = parseInt(n / 10);
}
n = singlesum;
}
console.log(singlesum);
}
digital_root(1632)
You can use recursion to solve this.
Write a function makeSingleDigit, which argument will be your number.
You need a base condition with the base step, which in your case stops the recursion when received number is one-digit and returns the number.
If condition is not true, you just need to get another digit from the number by n%10 and sum it with the makeSingleDigit(Math.floor(n/10)). By this, you repeatedly sum digits of new numbers, until function receives one-digit number.
Mathematical solution just for your information: the number, which you want to find is n % 9 === 0 ? 9 : n % 9, thus it is the remainder of the division by 9 if it is not 0, otherwise it is 9.
Here is a very optimal solution to the problem:
function digital_root(n) {
return (n - 1) % 9 + 1;
}
const result = digital_root(1632);
console.log(result);
Well, not a very good solution but you can give a hit.
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
return(digits);
}
}
var num = 1632;
do{
num = digital_root(num);
}while(num>10);
I'm looking for a way to check if a string is periodic or not using JavaScript.
Sample string to match can be 11223331122333. Whereas, 10101 should not match.
Coming from python, I used the RegEx
/(.+?)\1+$/
But it is quite slow. Are there any string methods that can do the trick?
The idea of the code below is to consider substrings of all lengths the original string can be divided into evenly, and to check whether they repeat across the original string. A simple method is to check all divisors of the length from 1 to the square root of the length. They are divisors if the division yields an integer, which is also a complementary divisor. E.g., for a string of length 100 the divisors are 1, 2, 4, 5, 10, and the complementary divisors are 100 (not useful as substring length because the substring would appear only once), 50, 25, 20 (and 10, which we already found).
function substr_repeats(str, sublen, subcount)
{
for (var c = 0; c < sublen; c++) {
var chr = str.charAt(c);
for (var s = 1; s < subcount; s++) {
if (chr != str.charAt(sublen * s + c)) {
return false;
}
}
}
return true;
}
function is_periodic(str)
{
var len = str.length;
if (len < 2) {
return false;
}
if (substr_repeats(str, 1, len)) {
return true;
}
var sqrt_len = Math.sqrt(len);
for (var n = 2; n <= sqrt_len; n++) { // n: candidate divisor
var m = len / n; // m: candidate complementary divisor
if (Math.floor(m) == m) {
if (substr_repeats(str, m, n) || n != m && substr_repeats(str, n, m)) {
return true;
}
}
}
return false;
}
Unfortunately there is no String method for comparing to a substring of another string in place (e.g., in C language that would be strncmp(str1, str2 + offset, length)).
Say your string has a length of 120, and consists of a substring of length 6 repeated 20 times. You can look at it also as consisting of a sublength (length of substring) 12 repeated 10 times, sublength 24 repeated 5 times, sublength 30 repeated 4 times, or sublength 60 repeated 2 times (the sublengths are given by the prime factors of 20 (2*2*5) applied in different combinations to 6). Now, if you check whether your string contains a sublength of 60 repeated 2 times, and the check fails, you can also be sure that it won't contain any sublength which is a divisor (i.e., a combination of prime factors) of 60, including 6. In other words, many checks made by the above code are redundant. E.g., in the case of length 120, the above code checks (luckily failing quickly most of the time) the following sublengths: 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60 (in this order: 1, 60, 2, 40, 3, 30, 4, 24, 5, 20, 6, 15, 8, 12, 10). Of these, only the following are necessary: 24, 40, 60. These are 2*2*2*3, 2*2*2*5, 2*2*3*5, i.e., the combinations of primes of 120 (2*2*2*3*5) with one of each (nonrepeating) prime taken out, or, if you prefer, 120/5, 120/3, 120/2. So, forgetting for a moment that efficient prime factorization is not a simple task, we can restrict our checks of repeating substrings to p substrings of sublength length/p, where p is a prime factor of length. The following is the simplest nontrivial implementation:
function substr_repeats(str, sublen, subcount) { see above }
function distinct_primes(n)
{
var primes = n % 2 ? [] : [2];
while (n % 2 == 0) {
n /= 2;
}
for (var p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
primes.push(p);
n /= p;
while (n % p == 0) {
n /= p;
}
}
}
if (n > 1) {
primes.push(n);
}
return primes;
}
function is_periodic(str)
{
var len = str.length;
var primes = distinct_primes(len);
for (var i = primes.length - 1; i >= 0; i--) {
var sublen = len / primes[i];
if (substr_repeats(str, sublen, len / sublen)) {
return true;
}
}
return false;
}
Trying out this code on my Linux PC I had a surprise: on Firefox it was much faster than the first version, but on Chromium it was slower, becoming faster only for strings with lengths in the thousands. At last I found out that the problem was related to the array that distinct_primes() creates and passes to is_periodic(). The solution was to get rid of the array by merging these two functions. The code is below and the test results are on http://jsperf.com/periodic-strings-1/5
function substr_repeats(str, sublen, subcount) { see at top }
function is_periodic(str)
{
var len = str.length;
var n = len;
if (n % 2 == 0) {
n /= 2;
if (substr_repeats(str, n, 2)) {
return true;
}
while (n % 2 == 0) {
n /= 2;
}
}
for (var p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
if (substr_repeats(str, len / p, p)) {
return true;
}
n /= p;
while (n % p == 0) {
n /= p;
}
}
}
if (n > 1) {
if (substr_repeats(str, len / n, n)) {
return true;
}
}
return false;
}
Please remember that the timings collected by jsperf.org are absolute, and that different experimenters with different machines will contribute to different combinations of channels. You need to edit a new private version of the experiment if you want to reliably compare two JavaScript engines.
One option is to continue using a regex, but to make it greedy by dropping the ?:
/^(.+)\1+$/
Depending on the exact input strings, it may reduce the amount of backtracking required and speed up the matching.
If a string is periodic:
The last element would be the last element of the period as well
The period length would divide the string length
So we can make a super greedy algorithm that takes the last element and checks for occurrences up until half of the length. When we find one, we check if the substring's length divides the main length and only after that we would test against the string.
function periodic(str){
for(var i=0; i<=str.length/2; i++){
if(str[i] === str[str.length-1] && str.length%(i+1) === 0){
if (str.substr(0,i+1).repeat(str.length/(i+1)) === str){
return true;
}
}
}
return false;
}
A direct approach is to divide the string into equal-sized chunks and test
whether each chuck is the same as the first chunk. Here is an algorithm does
that by increasing the chunk size from 1 to length/2, skipping chunk sizes
that do not cleanly divide the length.
function StringUnderTest (str) {
this.str = str;
this.halfLength = str.length / 2;
this.period = 0;
this.divideIntoLargerChunksUntilPeriodicityDecided = function () {
this.period += 1;
if (this.period > this.halfLength)
return false;
if (this.str.length % this.period === 0)
if (this.currentPeriodOk())
return true;
return this.divideIntoLargerChunksUntilPeriodicityDecided();
};
this.currentPeriodOk = function () {
var patternIx;
var chunkIx;
for (chunkIx=this.period; chunkIx<this.str.length; chunkIx+=this.period)
for (patternIx=0; patternIx<this.period; ++patternIx)
if (this.str.charAt(patternIx) != this.str.charAt(chunkIx+patternIx))
return false;
return true;
};
}
function isPeriodic (str) {
var s = new StringUnderTest(str);
return s.divideIntoLargerChunksUntilPeriodicityDecided();
}
I have not tested the speed, though...
There is an answer which deserves mentioning for its sheer beauty. It's not mine, I have only adapted it from the Python version, which is here: How can I tell if a string repeats itself in Python?
function is_periodic(s)
{
return (s + s.substring(0, s.length >> 1)).indexOf(s, 1) > 0;
}
Unfortunately, the speed is not on par with the beauty (and also the beauty has suffered a bit in the adaptation from Python, since indexOf() has a start parameter, but not a stop parameter). A comparison with the regex solution(s) and with the functions of my other answer is here. Even with strings of random length in [4, 400] based on a small 4 character alphabet the functions of my other answer perform better. This solution is faster than the regex solution(s), though.
This solution might be called the “phaseshift solution”. The string is treated like a wave which is identical to itself when shifting its phase.
The advantage of this solution over the ones of my other answer is that it can be easily adapted to return the shortest repeating substring, like this:
function repeating_substr(s)
{
period = (s + s.substring(0, s.length >> 1)).indexOf(s, 1);
return period > 0 ? s.substr(0, period) : null;
}