Using Octave I want to take a number for example
x = 14
And split it into a matrix like the following.
m = [1, 4]
So far I've tried converting the number into a string, and then using the str2mat function without result.
Another example would be
x = 23445
Converted to
m = [2, 3, 4, 4, 5]
Thanks in advance for the help.
x = 14;
sprintf('%d',x) - '0'
>> 1 4
If you want to do this via string manipulation, provided there's no decimal parts, this is the way to go:
octave> x = 23445
x = 23445
octave> s = int2str (x)
s = 23445
octave> m = arrayfun (#(x) str2double (s(x)), 1:numel(s))
m =
2 3 4 4 5
Not tested, but the idea is: try to divide the number x = 23445 by 10 and take the decimal part.
For example, iterate:
x = 23445;
t = 23445/10; # t is 2344,5
r = floor(t); # r is 2344
d = x - r * 10 # d is 5 = 23445 - 2344 * 10
d will have value 5 (you have the last digit of x, add it to the array). r will have value 2344. So now:
x = r; # so x = 2344;
t = 2344/10; # t is 234,4
r = floor(t); # r is 234
d = x - r * 10 # d is 4 = 2344 - 234 * 10
d will have value 4. r will have value 234.
And iterate till r = 0.
Related
Given an integer N, how to efficiently find the count of numbers which are divisible by 7 (their reverse should also be divisible by 7) in the range:
[0, 10^N - 1]
Example:
For N=2, answer:
4 {0, 7, 70, 77}
[All numbers from 0 to 99 which are divisible by 7 (also their reverse is divisible)]
My approach, simple brute-force:
initialize count to zero
run a loop from i=0 till end
if a(i) % 7 == 0 && reverse(a(i)) % 7 == 0, then we increase the count
Note:
reverse(123) = 321, reverse(1200) = 21, for example!
Let's see what happens mod 7 when we add a digit, d, to a prefix, abc.
10 * abc + d =>
(10 mod 7 * abc mod 7) mod 7 + d mod 7
reversed number:
abc + d * 10^(length(prefix) =>
abc mod 7 + (d mod 7 * 10^3 mod 7) mod 7
Note is that we only need the count of prefixes of abc mod 7 for each such remainder, not the actual prefixes.
Let COUNTS(n,f,r) be the number of n-digit numbers such that n%7 = f and REVERSE(n)%7 = r
The counts are easy to calculate for n=1:
COUNTS(1,f,r) = 0 when f!=r, since a 1-digit number is the same as its reverse.
COUNTS(1,x,x) = 1 when x >= 3, and
COUNTS(1,x,x) = 2 when x < 3, since 7%3=0, 8%3=1, and 9%3=2
The counts for other lengths can be figured out by calculating what happens when you add each digit from 0 to 9 to the numbers characterized by the previous counts.
At the end, COUNTS(N,0,0) is the answer you are looking for.
In python, for example, it looks like this:
def getModCounts(len):
counts=[[0]*7 for i in range(0,7)]
if len<1:
return counts
if len<2:
counts[0][0] = counts[1][1] = counts[2][2] = 2
counts[3][3] = counts[4][4] = counts[5][5] = counts[6][6] = 1
return counts
prevCounts = getModCounts(len-1)
for f in range(0,7):
for r in range(0,7):
c = prevCounts[f][r]
rplace=(10**(len-1))%7
for newdigit in range(0,10):
newf=(f*10 + newdigit)%7
newr=(r + newdigit*rplace)%7
counts[newf][newr]+=c
return counts
def numFwdAndRevDivisible(len):
return getModCounts(len)[0][0]
#TEST
for i in range(0,20):
print("{0} -> {1}".format(i, numFwdAndRevDivisible(i)))
See if it gives the answers you're expecting. If not, maybe there's a bug I need to fix:
0 -> 0
1 -> 2
2 -> 4
3 -> 22
4 -> 206
5 -> 2113
6 -> 20728
7 -> 205438
8 -> 2043640
9 -> 20411101
10 -> 204084732
11 -> 2040990205
12 -> 20408959192
13 -> 204085028987
14 -> 2040823461232
15 -> 20408170697950
16 -> 204081640379568
17 -> 2040816769367351
18 -> 20408165293673530
19 -> 204081641308734748
This is a pretty good answer when counting up to N is reasonable -- way better than brute force, which counts up to 10^N.
For very long lengths like N=10^18 (you would probably be asked for a the count mod 1000000007 or something), there is a next-level answer.
Note that there is a linear relationship between the counts for length n and the counts for length n+1, and that this relationship can be represented by a 49x49 matrix. You can exponentiate this matrix to the Nth power using exponentiation by squaring in O(log N) matrix multiplications, and then just multiply by the single digit counts to get the length N counts.
There is a recursive solution using digit dp technique for any digits.
long long call(int pos , int Mod ,int revMod){
if(pos == len ){
if(!Mod && !revMod)return 1;
return 0;
}
if(dp[pos][Mod][revMod] != -1 )return dp[pos][Mod][revMod] ;
long long res =0;
for(int i= 0; i<= 9; i++ ){
int revValue =(base[pos]*i + revMod)%7;
int curValue = (Mod*10 + i)%7;
res += call(pos+1, curValue,revValue) ;
}
return dp[pos][Mod][revMod] = res ;
}
I was doing some interview problems when I ran into an interesting one that I could not think of a solution for. The problems states:
Design a function that takes in an array of integers. The last two numbers
in this array are 'a' and 'b'. The function should find if all of the
numbers in the array, when summed/subtracted in some fashion, are equal to
a mod b, except the last two numbers a and b.
So, for example, let us say we have an array:
array = [5, 4, 3, 3, 1, 3, 5].
I need to find out if there exists any possible "placement" of +/- in this array so that the numbers can equal 3 mod 5. The function should print True for this array because 5+4-3+3-1 = 8 = 3 mod 5.
The "obvious" and easy solution would be to try and add/subtract everything in all possible ways, but that is an egregiously time complex solution, maybe
O(2n).
Is there any way better to do this?
Edit: The question requires the function to use all numbers in the array, not any. Except, of course, the last two.
If there are n numbers, then there is a simple algorithm that runs in O (b * n): For k = 2 to n, calculate the set of integers x such that the sum or difference of the first k numbers is equal to x modulo b.
For k = 2, the set contains (a_0 + a_1) modulo b and (a_0 - a_1) modulo b. For k = 3, 4, ..., n you take the numbers in the previous set, then either add or subtract the next number in the array. And finally check if a is element of the last set.
O(b * n). Let's take your example, [5, 4, 3, 3, 1]. Let m[i][j] represent whether a solution exists for j mod 5 up to index i:
i = 0:
5 = 0 mod 5
m[0][0] = True
i = 1:
0 + 4 = 4 mod 5
m[1][4] = True
but we could also subtract
0 - 4 = 1 mod 5
m[1][1] = True
i = 2:
Examine the previous possibilities:
m[1][4] and m[1][1]
4 + 3 = 7 = 2 mod 5
4 - 3 = 1 = 1 mod 5
1 + 3 = 4 = 4 mod 5
1 - 3 = -2 = 3 mod 5
m[2][1] = True
m[2][2] = True
m[2][3] = True
m[2][4] = True
i = 3:
1 + 3 = 4 mod 5
1 - 3 = 3 mod 5
2 + 3 = 0 mod 5
2 - 3 = 4 mod 5
3 + 3 = 1 mod 5
3 - 3 = 0 mod 5
4 + 3 = 2 mod 5
4 - 3 = 1 mod 5
m[3][0] = True
m[3][1] = True
m[3][2] = True
m[3][3] = True
m[3][4] = True
We could actually stop there, but let's follow a different solution than the one in your example backwards:
i = 4:
m[3][2] True means we had a solution for 2 at i=3
=> 2 + 1 means m[4][3] = True
+ 1
+ 3
+ 3
- 4
(0 - 4 + 3 + 3 + 1) = 3 mod 5
I coded a solution based on the mathematical explanation provided here. I didn't comment the solution, so if you want an explanation, I recommend you read the answer!
def kmodn(l):
k, n = l[-2], l[-1]
A = [0] * n
count = -1
domath(count, A, l[:-2], k, n)
def domath(count, A, l, k, n):
if count == len(l):
boolean = A[k] == 1
print boolean
elif count == -1:
A[0] = 1; # because the empty set is possible
count += 1
domath(count, A, l, k, n)
else:
indices = [i for i, x in enumerate(A) if x == 1]
b = [0] * n
for i in indices:
idx1 = (l[count] + i) % n
idx2 = (i - l[count]) % n
b[idx1], b[idx2] = 1, 1
count += 1
A = b
domath(count, A, l, k, n)
Let's say I have to repeat the process of multiplying a variable by a constant and modulus the result by another constant, n times to get my desired result.
the obvious solution is iterating n times, but it's getting time consuming the greater n is.
Code example:
const N = 1000000;
const A = 123;
const B = 456;
var c = 789;
for (var i = 0; i < n; i++)
{
c = (c * a) % b;
}
log("Total: " + c);
Is there any algebraic solution to optimize this loop?
% has two useful properties:
1) (x % b) % b = x % b
2) (c*a) % b = ((c%b) * (a%b))%b
This implies that e.g.
(((c*a)%b)*a) % b = ((((c*a)%b)%b) * (a%b)) % b
= (((c*a) % b) * (a%b)) % b
= (c*a*a) % b
= (c*a^2) % b
Hence, in your case the final c that you compute is equivalent to
(c*a^n)%b
This can be computed efficiently using exponentiation by squaring.
To illustrate this equivalence:
def f(a,b,c,n):
for i in range(n):
c = (c*a)%b
return c
def g(a,b,c,n):
return (c*pow(a,n,b)) % b
a = 123
b = 456
c = 789
n = 10**6
print(f(a,b,c,n),g(a,b,c,n)) #prints 261, 261
First, note that c * A^n is never an exact multiple of B = 456 since the former is always odd and the latter is always even. You can generalize this by considering the prime factorizations of the numbers involved and see that no repetition of the factors of c and A will ever give you something that contains all the factors of B. This means c will never turn into 0 as a result of the iterated multiplication.
There are only 456 possible values for c * a mod B = 456; therefore, if you iterate the loop 456 times, you will see at least value of c repeated. Suppose the first value of c that repeats is c', when i= i'. Say it first saw c' when i=i''. By continuing to iterate the multiplication, we would expect to see c' again:
we saw it at i''
we saw it at i'
we should see it at i' + (i' - i'')
we should see it at i' + k(i' - i'') as well
Once you detect a repeat you know that pattern is going to repeat forever. Therefore, you can compute how many patterns are needed to get to N, and the offset in the repeating pattern that you'd be at for i = N - 1, and then you'd know the answer without actually performing the multiplications.
A simpler example:
A = 2
B = 3
C = 5
c[0] = 5
c[1] = 5 * 2 % 3 = 1
c[2] = 1 * 2 % 3 = 2
c[3] = 2 * 2 % 3 = 1 <= duplicate
i' = 3
i'' = 1
repeating pattern: 1, 2, 1
c[1+3k] = 1
c[2+3k] = 2
c[3+3k] = 1
10,000 = 1 + 3k for k = 3,333
c[10,000] = 1
c[10,001] = 2
c[10,002] = 1
I'm trying to write MATLAB code that will allow me to find the permutation matrices of a matrix.
Let's consider the example below. I'm given the matrices A and B:
A = [1 2 3;4 5 6; 7 8 9] % is a given matrix
B = [9 7 8;3 1 2; 6 4 5] % is a permuted version of A.
My goal is to find the matrices L (that pre-multiply A) and R (that post-multiply A) such that L*A*R = B:
% L is an n by n (3 by 3) that re-order the rows a matrix when it pre-multiply that matrix
L = [0 0 1;1 0 0;0 1 0]
% R is an n by n that re-order the columns of a matrix
R = [0 1 0;0 0 1;1 0 0]
B = L*A*R
How to find L and R when I know A and B?
To give a baseline solution, here is the brute-force method:
function [L,R] = find_perms(A,B)
[n,n] = size(A);
p = perms(1:n);
I = eye(n);
for i=1:size(p,1)
for j=1:size(p,1)
L = I(p(i,:),:);
R = I(:,p(j,:));
if isequal(L*A*R, B)
return;
end
end
end
% none found
L = [];
R = [];
end
Let's test it:
A = [1 2 3; 4 5 6; 7 8 9];
B = [9 7 8; 3 1 2; 6 4 5];
[L,R] = find_perms(A,B);
assert(isequal(L*A*R, B));
The left/right permutation matrices are as expected:
>> L
L =
0 0 1
1 0 0
0 1 0
>> R
R =
0 1 0
0 0 1
1 0 0
I am trying to get as good an estimate of pi as I can using the Chudnovsky algorithm in Python. This algorithm implies getting the square root of 640 320.
After doing some research, I found a quite effective way to compute square roots; the method is called "digit-by-digit calculation" (see here). So, after trying to implement it, I found out that the first 13 decimals are correct, and then I get strange results (the next one is a 0 instead of a 4, and then the next 'digit' is 128, then -1024...)
I tried checking my function, but it looks fine to me (besides, I would probably not find the correct first 13 decimals otherwise). Thus, my question is : are there some limits in this digit-by-digit calculation method?
If, by any chance, you would like to see my code, here it is:
def sqrt(input_number,accuracy):
"""input_number is a list that represents a number we want to get the square root of.
For example, 12.56 would be [[1,2], [5,6], '+']"""
if input_number[2]!="+":
raise ValueError("Cannot find the real square root of a negative number: '"+pl(input_number)+"'")
"""Below creates the right number of elements for the required accuracy of the
square root"""
if len(input_number[0])%2==1:
input_number[0].insert(0,0)
if len(input_number[1])<2*accuracy:
for i in range(2*accuracy-len(input_number[1])):
input_number[1].append(0)
if len(input_number[1])%2==1:
input_number[1].append(0)
# Below makes the pairs of digits required in the algorithm
pairs=[[10*input_number[0][2*i]+input_number[0][2*i+1] for i in range(int(len(input_number[0])/2))],[10*input_number[1][2*i]+input_number[1][2*i+1] for i in range(int(len(input_number[1])/2))]]
"""Performs the algorithm, where c,x,y and p have the same definition
as on the Wikipedia link above. r is the remainder. pairs[0] is the pairs
of digits before the decimal dot, and pairs[1] represents the pairs of
digits after the dot. square_root is the computed square root of input_number."""
p=0
r=0
square_root=[[],[],"+"]
for i in range(len(pairs[0])):
c=100*r+pairs[0][i]
x=int((-20*p+(400*p**2+4*c)**.5)/2)
y=20*p*x+x**2
r=c-y
p=10*p+x
square_root[0].append(x)
for i in range(len(pairs[1])):
print(p,r,c)
c=100*r+pairs[1][i]
x=int((-20*p+(400*p**2+4*c)**.5)/2)
y=20*p*x+x**2
r=c-y
p=10*p+x
square_root[1].append(x)
return square_root
The problem is this code.
x = int((-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2)
This code performs Floating-point subtraction. It causes loss of significance, because of two close numbers are subtracted.
>>> p = 10**15
>>> c = 10**15
>>> x = (-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2
>>> x
0.0
so, you should use integer sqrt instead of **.5. and change loop like this.
for i in range(len(pairs[0])):
c = 100 * r + pairs[0][i]
#x = int((-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2)
x = (-20 * p + isqrt(400 * p ** 2 + 4 * c)) // 2
y = 20 * p * x + x ** 2
r = c - y
p = 10 * p + x
square_root[0].append(x)
for i in range(len(pairs[1])):
#print(p,r,c)
c = 100 * r + pairs[1][i]
#x = int((-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2)
x = (-20 * p + isqrt(400 * p ** 2 + 4 * c)) // 2
y = 20 * p * x + x ** 2
r = c - y
p = 10 * p + x
square_root[1].append(x)
and define isqrt -- the integer sqrt function
# from http://stackoverflow.com/questions/15390807/integer-square-root-in-python
def isqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
Then, you could get an accurated value of sqrt(2).
>>> print( sqrt([[2], [0], '+'], 25) )
[[1], [4, 1, 4, 2, 1, 3, 5, 6, 2, 3, 7, 3, 0, 9, 5, 0, 4, 8, 8, 0, 1, 6, 8, 8, 7], '+']