the following error occurs. I tried to change the n .... but not working
"LoadError: BoundsError: attempt to access 9-element Array{Float64,1}:"
function bernstein_vandermonde( n )
if n == 1
v = ones(1, 1);
return v
end
v = zeros( n, n );
x = linspace( 0, 1, n );
for i = 1:n
println("entra no loop")
v[i,1:n] = bernstein_poly_01(n - 1, x[i])
end
return v
end
function bernstein_poly_01( n, x )
bern = ones(n)
if n == 0
bern[1] = 1
elseif 0 < n
bern[1] = 1 -x
bern[2] = x
for i = 2:n
bern[i+1] = x*bern[i];
for j = i-1:-1: 1
bern[j+1] = x*bern[j] + (1 - x)*bern[j+1]
end
bern[1] = (1 - x)*bern[1]
end
end
return bern
end
I can not solve :(
Related
i am new at Standard ML and i have a question , at the code below when
i run without the let-in structure , the code runs and gives result .When i put the the let-in
it shows syntax errors . Can anyone help me ?
fun findInd([],size, value , ans , l , h ) = ~1
| findInd(lista ,size, value , ans , l , h) =
let
val midval = Real.round((real l + real h) / real 2)
val Nelem = List.nth(lista,midval)
in
if l<=h then
if Nelem <= value then findInd(lista,size,value,midval,midval+1,h )
else findInd(lista,size,value,ans,l,midval+(~1) )
else
ans
end;
let (* <-- this let gives the problem *)
val s = 0
val sum = ref s
val maxlen = 0
val maxlenptr = ref maxlen
val counter_start = 0
val counter = ref counter_start
val arr = [1,5,~58,~1]
val presum = [~53,~52,1,6]
val minInd = [3,2,0,0
while !counter < List.length(arr) do (
sum := !sum + List.nth(arr,!counter);
if !sum >=0 then maxlenptr := !counter + 1
else
let
val ind = findInd(presum, List.length(arr) , s , ~1 ,0 , List.length(arr) + (~1) )
val temp = List.nth(minInd,ind)
in
if ind <> ~1 andalso temp < counter_start then maxlenptr := Int.max(!maxlenptr,counter_start + (~temp))
else ()
end;
counter := !counter + 1
);
val m = !maxlenptr
in (* <--- this in *)
m
end;
The syntax of let is let <declarations> in <expression> and a while loop is not a declaration. You'll need to move it after the in (like you did with the ifs in the other lets).
I am trying to write a program (in Lua, but I guess this is more of a mathematical problem) that calculates the total distance between a set of numbers and there are two or three different possibilities for some of these numbers.
For example a set of numbers is: 2, 5, 0, 1. The sum of distances in this case is 9. (5-2 + 5-0 + 1-0)
The first row with alternatives is: 5, -, 3, 2.
The second row with alternatives is: 3, -, -, 3
The combination between the two rows with the smallest sum of distances is: 5, 5, 3, 3 with a sum of distances of 2.
My first attempt was to write a program that tries all possible iterations, but with a set of about 40 numbers, there are so many possibilities that my computer crashed...
Here is the code for that version, it first creates all the different possibilities and then calculates the differences and places them in column 0. Afterwards I can find the smallest value easily and see also the combination of numbers which results in that value.
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local imax = 1
local solution = {}
local answer = table1[1]
for x = 1,#table1 do
solution[x]={}
for i= 1, (2^imax)/2 do
solution[x][i] = table1[x]
end
if table2[x] ~= nil then -- there is an alternative number
for y = 1, x-1 do -- copy all the previous table entries except the last one
for j = ((2^imax)/2)+1, 2^imax do -- the number of new rows increases exponentially
solution[y][j] = solution[y][j-imax]
end
end
for j = ((2^imax)/2)+1, 2^imax do -- create the new table entry with the alternative number
solution[x][j] = table2[x]
end
imax = imax + 1 -- this number is to remind how many alternative numbers where found
end
end
solution[0]={}
for x = 1, #table1 do
for i = 1, (2^imax)/2 do
if x < #table1 then answer = math.sqrt((solution[x+1][i]-solution[x][i])^2) else answer = 0 end
if solution[0][i] == nil then solution[0][i] = answer else solution[0][i] = solution[0][i] + answer end
end
end
After reading about dynamic programming, I wrote a new version of this program. It calculates the smallest sum of differences, but I also want to know the path (the combination of numbers) to that sum... Still work to do...
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local solution = {}
local smallestsolution = {}
solution[1]={}
solution[2]={}
solution[3]={}
solution[4]={}
for i = 1, (#table1-1) do
solution[1][i] = math.sqrt((table1[i+1]-table1[i])^2)
if table2[i] ~= nil then solution[2][i] = math.sqrt((table1[i+1]-table2[i])^2) end
if table2[i+1] ~= nil then solution[3][i] = math.sqrt((table2[i+1]-table1[i])^2) end
if table2[i] ~= nil and table2[i+1] ~= nil then solution[4][i] = math.sqrt((table2[i+1]-table2[i])^2) end
end
for i = 1, (#table1-1) do
smallestsolution[i]=100000
for j = 1, 4 do
if solution[j][i] ~= nil and solution[j][i] < smallestsolution[i] then smallestsolution[i]=solution[j][i] end
end
end
local smallestsum = 0
for i = 1, (#table1-1) do
smallestsum = smallestsum + smallestsolution[i]
end
Thanks,
Emile
I managed to solve it myself! The hint to dynamic programming by #EgorSkriptunoff did the trick!
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local solution = {}
local smallestsolution = {}
solution[1]={}
solution[2]={}
solution[3]={}
solution[4]={}
local path = {}
local temp = {}
for i = 1, (#table1-1) do
solution[1][i] = math.sqrt((table1[i+1]-table1[i])^2)
if table2[i] ~= nil then solution[2][i] = math.sqrt((table1[i+1]-table2[i])^2) end
if table2[i+1] ~= nil then solution[3][i] = math.sqrt((table2[i+1]-table1[i])^2) end
if table2[i] ~= nil and table2[i+1] ~= nil then solution[4][i] = math.sqrt((table2[i+1]-table2[i])^2) end
end
for i = 1, (#table1-1) do
smallestsolution[i]=100000
temp[i] = 0
for j = 1, 4 do
if solution[j][i] ~= nil and solution[j][i] < smallestsolution[i] then smallestsolution[i]=solution[j][i] temp[i] = j end
end
end
local smallestsum = 0
for i = 1, (#table1-1) do
smallestsum = smallestsum + smallestsolution[i]
end
for i = 1, (#table1) do -- find the path belonging to the smallest sum of differences
if temp[i] == 1 then path[i] = table1[i] end
if temp[i] == 2 then path[i] = table2[i] end
if temp[i] == 3 then path[i] = table1[i] end
if temp[i] == 4 then path[i] = table2[i] end
if i == (#table1) then
if temp[i-1] == 1 then path[i] = table1[i] end
if temp[i-1] == 2 then path[i] = table1[i] end
if temp[i-1] == 3 then path[i] = table2[i] end
if temp[i-1] == 4 then path[i] = table2[i] end
end
end
Im currently working on a project about the multiple encryption method! I am having a lot of trouble with RSA. I have a code that encrypt, give the public and the private key. Now I need to let someone write the private key and the encrypted text, and make the program decrypt it. I tried many times, ando got so many different erros that I deleted the decrypt function to do it over from start. Could anyone shine some ligth upon me? How to do, what should I do... Any help, really.
This is the code:
import random
def totient(number):
if(prime(number)):
return number-1
else:
return False
def prime(n):
if (n <= 1):
return False
if (n <= 3):
return True
if (n%2 == 0 or n%3 == 0):
return False
i = 5
while(i * i <= n):
if (n%i == 0 or n%(i+2) == 0):
return False
i+=6
return True
def generate_E(num):
def mdc(n1,n2):
rest = 1
while(n2 != 0):
rest = n1%n2
n1 = n2
n2 = rest
return n1
while True:
e = random.randrange(2,num)
if(mdc(num,e) == 1):
return e
def generate_prime():
while True:
x=random.randrange(1,100)
if(prime(x)==True):
return x
def mod(a,b):
if(a<b):
return a
else:
c=a%b
return c
def cipher(words,e,n):
tam = len(words)
i = 0
lista = []
while(i < tam):
letter = words[i]
k = ord(letter)
k = k**e
d = mod(k,n)
lista.append(d)
i += 1
return lista
def calculate_private_key(toti,e):
d = 0
while(mod(d*e,toti)!=1):
d += 1
return d
## MAIN
if __name__=='__main__':
text = input("Insert message: ")
p = generate_prime() # generates random P
q = generate_prime() # generates random Q
n = p*q # compute N
y = totient(p) # compute the totient of P
x = totient(q) # compute the totient of Q
totient_de_N = x*y # compute the totient of N
e = generate_E(totient_de_N) # generate E
public_key = (n, e)
print('Your public key:', public_key)
text_cipher = cipher(text,e,n)
print('Your encrypted message:', text_cipher)
d = calculate_private_key(totient_de_N,e)
print('Your private key is:', d)
Modular inverses can be computed as follows (from Rosetta Code):
#include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
However, the inputs are ints, as you can see. Would the above code work for unsigned integers (e.g. uint64_t) as well? I mean, would it be ok to replaced all int with uint64_t? I could try for few inputs but it is not feasible to try for all 64-bits combinations.
I'm specifically interested in two aspects:
for values [0, 264) of both a and b, would all calculation not overflow/underflow (or overflow with no harm)?
how would (x1 < 0) look like in unsigned case?
First of all how this algorithm works? It is based on the Extended Euclidean algorithm for computation of the GCD. In short the idea is following: if we can find some integer coefficients m and n such that
a*m + b*n = 1
then m will be the answer for the modular inverse problem. It is easy to see because
a*m + b*n = a*m (mod b)
Luckily the Extended Euclidean algorithm does exactly that: if a and b are co-prime, it finds such m and n. It works in the following way: for each iteration track two triplets (ai, xai, yai) and (bi, xbi, ybi) such that at every step
ai = a0*xai + b0*yai
bi = a0*xbi + b0*ybi
so when finally the algorithm stops at the state of ai = 0 and bi = GCD(a0,b0), then
1 = GCD(a0,b0) = a0*xbi + b0*ybi
It is done using more explicit way to calculate modulo: if
q = a / b
r = a % b
then
r = a - q * b
Another important thing is that it can be proven that for positive a and b at every step |xai|,|xbi| <= b and |yai|,|ybi| <= a. This means there can be no overflow during calculation of those coefficients. Unfortunately negative values are possible, moreover, on every step after the first one in each equation one is positive and the other is negative.
What the code in your question does is a reduced version of the same algorithm: since all we are interested in is the x[a/b] coefficients, it tracks only them and ignores the y[a/b] ones. The simplest way to make that code work for uint64_t is to track the sign explicitly in a separate field like this:
typedef struct tag_uint64AndSign {
uint64_t value;
bool isNegative;
} uint64AndSign;
uint64_t mul_inv(uint64_t a, uint64_t b)
{
if (b <= 1)
return 0;
uint64_t b0 = b;
uint64AndSign x0 = { 0, false }; // b = 1*b + 0*a
uint64AndSign x1 = { 1, false }; // a = 0*b + 1*a
while (a > 1)
{
if (b == 0) // means original A and B were not co-prime so there is no answer
return 0;
uint64_t q = a / b;
// (b, a) := (a % b, b)
// which is the same as
// (b, a) := (a - q * b, b)
uint64_t t = b; b = a % b; a = t;
// (x0, x1) := (x1 - q * x0, x0)
uint64AndSign t2 = x0;
uint64_t qx0 = q * x0.value;
if (x0.isNegative != x1.isNegative)
{
x0.value = x1.value + qx0;
x0.isNegative = x1.isNegative;
}
else
{
x0.value = (x1.value > qx0) ? x1.value - qx0 : qx0 - x1.value;
x0.isNegative = (x1.value > qx0) ? x1.isNegative : !x0.isNegative;
}
x1 = t2;
}
return x1.isNegative ? (b0 - x1.value) : x1.value;
}
Note that if a and b are not co-prime or when b is 0 or 1, this problem has no solution. In all those cases my code returns 0 which is an impossible value for any real solution.
Note also that although the calculated value is really the modular inverse, simple multiplication will not always produce 1 because of the overflow at multiplication over uint64_t. For example for a = 688231346938900684 and b = 2499104367272547425 the result is inv = 1080632715106266389
a * inv = 688231346938900684 * 1080632715106266389 =
= 743725309063827045302080239318310076 =
= 2499104367272547425 * 297596738576991899 + 1 =
= b * 297596738576991899 + 1
But if you do a naive multiplication of those a and inv of type uint64_t, you'll get 4042520075082636476 so (a*inv)%b will be 1543415707810089051 rather than expected 1.
The mod_inv C function :
return a modular multiplicative inverse of n with respect to the modulus
return 0 if the linear congruence has no solutions
unsigned mod_inv(unsigned n, const unsigned mod) {
unsigned a = mod, b = a, c = 0, d = 0, e = 1, f, g;
for (n *= a > 1; n > 1 && (n *= a > 0); e = g, c = (c & 3) | (c & 1) << 2) {
g = d, d *= n / (f = a);
a = n % a, n = f;
c = (c & 6) | (c & 2) >> 1;
f = c > 1 && c < 6;
c = (c & 5) | (f || e > d ? (c & 4) >> 1 : ~c & 2);
d = f ? d + e : e > d ? e - d : d - e;
}
return n ? c & 4 ? b - e : e : 0;
}
Examples
n = 7 and mod = 45 then res = 13 so 1 == ( 13 * 7 ) % 45
n = 52 and mod = 107 then res = 35 so 1 == ( 35 * 52 ) % 107
n = 213 and mod = 155 then res = 147 so 1 == ( 147 * 213 ) % 155
n = 392 and mod = 45 then res = 38 so 1 == ( 38 * 392 ) % 45
n = 3708141711 and mod = 4280761040 it still works...
i've been trying to turn the recurrence formula underneath into a pseudocode that uses memoization, however currently all i know is my below attempt is incorrect, is anyone able to point me in the right direction?
My recurrence formula:
N(C,i) =
1 if C = 0
0 if i=0 or C<0}
N(C-p_i, i-1) + N(C, i-1) otherwise
My current attempt:
MEM-N(C, i, r)
if r[i] >= 0 then
return r[i]
if i = 0 and r[i] >= 0 or C < 0 and r[i] >= 0 then
return 0
else if C = 0 and r[i] >= 0 then
return 1
else
q = -$\infty$
q = MEM-N(C - $p_i$, i-1) + MEM-N(C,i - x, r)
r[i] = q
return q
Following on from the comments:
MEM-N(C, i, r)
if C = 0 then
return 1
else if i = 0 or C < 0 then
return 0
else if r[i] >= 0 then
return r[i] # move here
else
q = MEM-N(C - p_i, i - 1, r) + MEM-N(C, i - 1, r) # fix
r[i] = q
return q