Exponentiation - positional system based on three - algorithm

I have a natural number x in the decimal system and natural number n in a ternary numeral system. How to calculate the value of x^n using the minimum number of multiplications?
I know the algorithm for a binary system and I was looking for an analogy, but I did not find it.

Perhaps you need something like this:
function expbycubing(x, n):
//treat n = 0..2 cases here
switch n % 3:
0: return expbycubing(x * x * x, n shrt 1)
///// note shift in ternary system (tri)201 => (tri)020
1: return x * expbycubing(x * x * x, n shrt 1)
2: return x * x * expbycubing(x * x * x, n shrt 1)
Working Delphi code
function expbycubing(x, n: Integer): int64;
begin
Memo1.Lines.Add(Format('x: %d n: %d', [x, n]));
if n = 0 then Exit(1);
if n = 1 then Exit(x);
if n = 2 then Exit(x * x);
case n mod 3 of
0: Result := expbycubing(x * x * x, n div 3);
1: Result := x * expbycubing(x * x * x, n div 3);
2: Result := x * x * expbycubing(x * x * x, n div 3);
end;
end;
var
i: Integer;
begin
for i := 12 to 12 do
Memo1.Lines.Add(Format('%d: %d', [i, expbycubing(2, i)]));
end;
log:
x: 2 n: 12
x: 8 n: 4
x: 512 n: 1
12: 4096

Related

The '+' operation is not applicable to the types function(x: real): real and real. Check the operation of the program for a = 0.1; b = 1.0; h = 0.1;

Check the operation of the program for a = 0.1; b = 1.0; h = 0.1; select the value of parameter n depending on the task.
Why am I getting an error? What is the best way to solve this problem? How to simplify?
var i, n: integer;
x, k, h, sx: real;
function Y(x: real): real;
begin
Y := x * arctan(x) - 0.5 * ln(1.0 + x * x)
end;
function S(x: real): real;
var sum, xx, p, znak, e: real;
begin
S := 0.5 * x * x;
p := x * x;
xx := - x * x;
k := 2;
e := 1e303;
while abs(e) > 1e-14 do
begin
k := k + 2;
p := p * xx;
e := p / (k * (k - 1));
S := S + e
end
end;
begin
h := 0.1;
writeln('x': 2, 'S(x)': 14,
'Y(x)': 18, 'n': 15);
for i := 1 to 10 do
begin
x := i * h;
sx := S(x);
n := round(k / 2);
writeln(x: 3: 1, sx: 18: 14,
Y(x): 18: 14, n: 10)
end
end.
-->The '+' operation is not applicable to the types function(x: real): real and real
I tried to solve the problem based on the fact that x is the range a to b with a step h:
program test;
var y, a, b, h, x, Sx, Yx, n:real;
begin
a:=0.1;
b:=1.0;
h:=0.1;
x:=a;
n:=0;
while x<=b do
begin
Yx:= x*arctan(x)-ln(sqrt(1+exp(x)));
x:=x+h;
writeln(Yx);
writeln('---------------------', n); n:=n+1;
end;
end.
But I do not know how to get S(x)
The error message means that the first argument of + is a function. I'll bet this is the S := S + e line. While you can assign to S to set the return value of S, you can't read it back like that.
You can refer to a function inside that function; this is used with recursion. But then you'll need to actually call yourself. E.g. Fibonacci := Fibonacci(i-1) * i. Now the left side of * is not a function, but the result of a function call.
Solution: just use a temporary variable, and assign that to S at the very end; of S

Algorithm for expressing given number as a sum of two squares

My problem is as follows:
I'm given a natural number n and I want to find all natural numbers x and y such that
n = x² + y²
Since this is addition order does not matter so I count (x,y) and (y,x) as one solution.
My initial algorithm is to assume that y>x, for all x compute y²=n-x² and check if y is a natural number using binary search on y².
for(x=1;2*x*x<n;x++)
{
y_squared=n-x*x;
if(isSquare(y_squared)==false)
continue;
//rest of the code
}
Is there any improvement for my algorithm? I already checked if n can have solutions using two squares theorem, but I want to know how many there are.
My algorithm is O(sqrt(n) * log(n) )
Thanks in advance.
You can reduce this to O(sqrt(n)) this way:
all_solutions(n):
x = 0
y = floor(sqrt(n))
while x <= y
if x * x + y * y < n
x++
else if x * x + y * y > n
y--
else
// found a match
print(x, y)
x++
y--
This algorithm will find and print all possible solutions and will always terminate for x <= sqrt(n / 2) and y >= sqrt(n / 2), leading to at most sqrt(n / 2) + (sqrt(n) - sqrt(n / 2)) = sqrt(n) iterations being performed.
A variation of Paul's, keeping track of the sum of squares and adjusting it just with additions/subtractions:
Pseudo-code: (evaluate x++ + x and y-- + y left-to-right, or do it like in the Python code below)
x = 0
y = floor(sqrt(n))
sum = y * y
while x <= y
if sum < n
sum += x++ + x
else if sum > n
sum -= y-- + y
else
print(x, y)
sum += 2 * (++x - y--)
Java:
static void allSolutions(int n) {
int x = 0, y = (int) Math.sqrt(n), sum = y * y;
while (x <= y) {
if (sum < n) {
sum += x++ + x;
} else if (sum > n) {
sum -= y-- + y;
} else {
System.out.println(x + " " + y);
sum += 2 * (++x - y--);
}
}
}
Python:
from math import isqrt
def all_solutions(n):
x = 0
y = isqrt(n)
sum = y ** 2
while x <= y:
if sum < n:
x += 1
sum += 2 * x - 1
elif sum > n:
sum -= 2 * y - 1
y -= 1
else:
# found a match
print(x, y)
x += 1
sum += 2 * (x - y)
y -= 1
Demo:
>>> all_solutions(5525)
7 74
14 73
22 71
25 70
41 62
50 55

For integers A>0, B>0, N>0, find integers x>0,y>0 such that N-(Ax+By) is smallest non-negative

Example :
A=5, B=2, N=12
Then let x=2, y=1, so 12 - (5(2) + 2(1)) = 0.
Another example:
A=5, B=4, N=12
Here x=1, y=1 is the best possible. Note x=2, y=0 would be better except that x=0 is not allowed.
I'm looking for something fast.
Note it's sufficient to find the value of Ax+By. It's not necessary to give x or y explicitly.
If gcd(A,B)|N, then N is your maximal value. Otherwise, it's the greatest multiple of gcd(A,B) that's smaller than N. Using 4x+2y=13 as an example, that value is gcd(4,2)*6=12 realized by 4(2)+2(2)=12 (among many solutions).
As a formula, your maximal value is Floor(N/gcd(A,B))*gcd(A,B).
Edit: If both x and y must be positive, this may not work. However, won't even be a solution if A+B>N. Here's an algorithm for you...
from math import floor, ceil
def euclid_wallis(m, n):
col1 = [1, 0, m]
col2 = [0, 1, n]
while col2[-1] != 0:
f = -1 * (col1[-1] // col2[-1])
col2, col1 = [x2 * f + x1 for x1, x2 in zip(col1, col2)], col2
return col1, col2
def positive_solutions(A, B, N):
(x, y, gcf), (cx, cy, _) = euclid_wallis(A, B)
f = N // gcf
while f > 0:
fx, fy, n = f*x, f*y, f*gcf
k_min = (-fx + 0.) / cx
k_max = (-fy + 0.) / cy
if cx < 0:
k_min, k_max = k_max, k_min
if floor(k_min) + 1 <= ceil(k_max) - 1:
example_k = int(floor(k_min) + 1)
return fx + cx * example_k, fy + cy * example_k, n
if k_max <= 1:
raise Exception('No solution - A: {}, B: {}, N: {}'.format(A, B, N))
f -= 1
print positive_solutions(5, 4, 12) # (1, 1, 9)
print positive_solutions(2, 3, 6) # (1, 1, 5)
print positive_solutions(23, 37, 238) # (7, 2, 235)
A brute-force O(N^2 / A / B) algorithm, implemented in plain Python3:
import math
def axby(A, B, N):
return [A * x + B * y
for x in range(1, 1 + math.ceil(N / A))
for y in range(1, 1 + math.ceil(N / B))
if (N - A * x - B * y) >= 0]
def bestAxBy(A, B, N):
return min(axby(A, B, N), key=lambda x: N - x)
This matched your examples:
In [2]: bestAxBy(5, 2, 12)
Out[2]: 12 # 5 * (2) + 2 * (1)
In [3]: bestAxBy(5, 4, 12)
Out[3]: 9 # 5 * (1) + 4 * (1)
Have no idea what algorithm that might be, but I think you need something like that (C#)
static class Program
{
static int solve( int a, int b, int N )
{
if( a <= 0 || b <= 0 || N <= 0 )
throw new ArgumentOutOfRangeException();
if( a + b > N )
return -1; // Even x=1, y=1 still more then N
int x = 1;
int y = ( N - ( x * a ) ) / b;
int zInitial = a * x + b * y;
int zMax = zInitial;
while( true )
{
x++;
y = ( N - ( x * a ) ) / b;
if( y <= 0 )
return zMax; // With that x, no positive y possible
int z = a * x + b * y;
if( z > zMax )
zMax = z; // Nice, found better
if( z == zInitial )
return zMax; // x/y/z are periodical, returned where started, meaning no new values are expected
}
}
static void Main( string[] args )
{
int r = solve( 5, 4, 12 );
Console.WriteLine( "{0}", r );
}
}

Can anyone explain how this division algorithm works?

I saw this in an algorithm textbook. I am confused about the middle recursive function. If you can explain it with an example, such as 4/2, that would be great!
function divide(x, y)
Input: Two n-bit integers x and y, where y ≥ 1
Output: The quotient and remainder of x divided by y
if x = 0: return (q, r) = (0, 0)
(q, r) = divide(floor(x/2), y)
q = 2 · q, r = 2 · r
if x is odd: r = r + 1
if r ≥ y: r = r − y, q = q + 1
return (q, r)
You're seeing how many times it's divisible by 2. This is essentially performing bit shifts and operating on the binary digits. A more interesting case would be 13/3 (13 is 1101 in binary).
divide(13, 3) // initial binary value - 1101
divide(6, 3) // shift right - 110
divide(3, 3) // shift right - 11
divide(1, 3) // shift right - 1 (this is the most significant bit)
divide(0, 3) // shift right - 0 (no more significant bits)
return(0, 0) // roll it back up
return(0, 1) // since x is odd (1)
return(1, 0) // r = r * 2 = 2; x is odd (3) so r = 3 and the r > y condition is true
return(2, 0) // q = 2 * 1; r = 2 * 1 - so r >= y and q = 2 + 1
return(4, 1) // q = 2 * 2; x is odd to r = 0 + 1

Matrix and algorithm "spiral"

i wanted ask if there some algorithm ready, that allowed me to do this: i have a matrix m (col) x n (row) with m x n elements. I want give position to this element starting from center and rotating as a spiral, for example, for a matrix 3x3 i have 9 elements so defined:
5 6 7
4 9 8
3 2 1
or for una matrix 4 x 3 i have 12 elements, do defined:
8 9 10 1
7 12 11 2
6 5 4 3
or again, a matrix 5x2 i have 10 elements so defined:
3 4
7 8
10 9
6 5
2 1
etc.
I have solved basically defining a array of integer of m x n elements and loading manually the value, but in generel to me like that matrix maked from algorithm automatically.
Thanks to who can help me to find something so, thanks very much.
UPDATE
This code, do exactely about i want have, but not is in delphi; just only i need that start from 1 and not from 0. Important for me is that it is valid for any matrics m x n. Who help me to translate it in delphi?
(defun spiral (rows columns)
(do ((N (* rows columns))
(spiral (make-array (list rows columns) :initial-element nil))
(dx 1) (dy 0) (x 0) (y 0)
(i 0 (1+ i)))
((= i N) spiral)
(setf (aref spiral y x) i)
(let ((nx (+ x dx)) (ny (+ y dy)))
(cond
((and (< -1 nx columns)
(< -1 ny rows)
(null (aref spiral ny nx)))
(setf x nx
y ny))
(t (psetf dx (- dy)
dy dx)
(setf x (+ x dx)
y (+ y dy)))))))
> (pprint (spiral 6 6))
#2A ((0 1 2 3 4 5)
(19 20 21 22 23 6)
(18 31 32 33 24 7)
(17 30 35 34 25 8)
(16 29 28 27 26 9)
(15 14 13 12 11 10))
> (pprint (spiral 5 3))
#2A ((0 1 2)
(11 12 3)
(10 13 4)
(9 14 5)
(8 7 6))
Thanks again very much.
Based on the classic spiral algorithm. supporting non-square matrix:
program SpiralMatrix;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TMatrix = array of array of Integer;
procedure PrintMatrix(const a: TMatrix);
var
i, j: Integer;
begin
for i := 0 to Length(a) - 1 do
begin
for j := 0 to Length(a[0]) - 1 do
Write(Format('%3d', [a[i, j]]));
Writeln;
end;
end;
var
spiral: TMatrix;
i, m, n: Integer;
row, col, dx, dy,
dirChanges, visits, temp: Integer;
begin
m := 3; // columns
n := 3; // rows
SetLength(spiral, n, m);
row := 0;
col := 0;
dx := 1;
dy := 0;
dirChanges := 0;
visits := m;
for i := 0 to n * m - 1 do
begin
spiral[row, col] := i + 1;
Dec(visits);
if visits = 0 then
begin
visits := m * (dirChanges mod 2) + n * ((dirChanges + 1) mod 2) - (dirChanges div 2) - 1;
temp := dx;
dx := -dy;
dy := temp;
Inc(dirChanges);
end;
Inc(col, dx);
Inc(row, dy);
end;
PrintMatrix(spiral);
Readln;
end.
3 x 3:
1 2 3
8 9 4
7 6 5
4 x 3:
1 2 3 4
10 11 12 5
9 8 7 6
2 x 5:
1 2
10 3
9 4
8 5
7 6
There you go!!! After 30some syntax errors...
On ideone.com, I ran it with some tests and it seems to work fine. I think you can see the output there still and run it yourself...
I put some comments in the code. Enough to understand most of it. The main navigation system is a little bit harder to explain. Briefly, doing a spiral is going in first direction 1 time, second 1 time, third 2 times, fourth 2 times, fifth 3 times, 3, 4, 4, 5, 5, and so on. I use what I called a seed and step to get this behavior.
program test;
var
w, h, m, n, v, d : integer; // Matrix size, then position, then value and direction.
spiral : array of array of integer; // Matrix/spiral itself.
seed, step : integer; // Used to travel the spiral.
begin
readln(h);
readln(w);
setlength(spiral, h, w);
v := w * h; // Value to put in spiral.
m := trunc((h - 1) / 2); // Finding center.
n := trunc((w - 1) / 2);
d := 0; // First direction is right.
seed := 2;
step := 1;
// Travel the spiral.
repeat
// If in the sub-spiral, store value.
if ((m >= 0) and (n >= 0) and (m < h) and (n < w)) then
begin
spiral[m, n] := v;
v := v - 1;
end;
// Move!
case d of
0: n := n + 1;
1: m := m - 1;
2: n := n - 1;
3: m := m + 1;
end;
// Plan trajectory.
step := step - 1;
if step = 0 then
begin
d := (d + 1) mod 4;
seed := seed + 1;
step := trunc(seed / 2);
end;
until v = 0;
// Print the spiral.
for m := 0 to (h - 1) do
begin
for n := 0 to (w - 1) do
begin
write(spiral[m, n], ' ');
end;
writeln();
end;
end.
If you really need that to print text spirals I'll let you align the numbers. Just pad them with spaces.
EDIT:
Was forgetting... In order to make it work on ideone, I put the parameters on 2 lines as input. m, then n.
For example:
5
2
yields
3 4
7 8
10 9
6 5
2 1
Here's the commented JavaScript implementation for what you're trying to accomplish.
// return an array representing a matrix of size MxN COLxROW
function spiralMatrix(M, N) {
var result = new Array(M * N);
var counter = M * N;
// start position
var curCol = Math.floor((M - 1) / 2);
var curRow = Math.floor(N / 2);
// set the center
result[(curRow * M) + curCol] = counter--;
// your possible moves RIGHT, UP, LEFT, DOWN * y axis is flipped
var allMoves = [[1,0], [0,-1], [-1,0], [0,1]];
var curMove = 0;
var moves = 1; // how many times to make current Move, 1,1,2,2,3,3,4,4 etc
// spiral
while(true) {
for(var i = 0; i < moves; i++) {
// move in a spiral outward counter clock-wise direction
curCol += allMoves[curMove][0];
curRow += allMoves[curMove][1];
// naively skips locations that are outside of the matrix bounds
if(curCol >= 0 && curCol < M && curRow >= 0 && curRow < N) {
// set the value and decrement the counter
result[(curRow * M) + curCol] = counter--;
// if we reached the end return the result
if(counter == 0) return result;
}
}
// increment the number of times to move if necessary UP->LEFT and DOWN->RIGHT
if(curMove == 1 || curMove == 3) moves++;
// go to the next move in a circular array fashion
curMove = (curMove + 1) % allMoves.length;
}
}
The code isn't the most efficient, because it walks the spiral naively without first checking if the location it's walking on is valid. It only checks the validity of the current location right before it tries to set the value on it.
Even though the question is already answered, this is an alternative solution (arguably simpler).
The solution is in python (using numpy for bidimendional arrays), but can be easily ported.
The basic idea is to use the fact that the number of steps is known (m*n) as end condition,
and to properly compute the next element of the loop at each iteration:
import numpy as np
def spiral(m, n):
"""Return a spiral numpy array of int with shape (m, n)."""
a = np.empty((m, n), int)
i, i0, i1 = 0, 0, m - 1
j, j0, j1 = 0, 0, n - 1
for k in range(m * n):
a[i, j] = k
if i == i0 and j0 <= j < j1: j += 1
elif j == j1 and i0 <= i < i1: i += 1
elif i == i1 and j0 < j <= j1: j -= 1
elif j == j0 and 1 + i0 < i <= i1: i -= 1
else:
i0 += 1
i1 -= 1
j0 += 1
j1 -= 1
i, j = i0, j0
return a
And here some outputs:
>>> spiral(3,3)
array([[0, 1, 2],
[7, 8, 3],
[6, 5, 4]])
>>> spiral(4,4)
array([[ 0, 1, 2, 3],
[11, 12, 13, 4],
[10, 15, 14, 5],
[ 9, 8, 7, 6]])
>>> spiral(5,4)
array([[ 0, 1, 2, 3],
[13, 14, 15, 4],
[12, 19, 16, 5],
[11, 18, 17, 6],
[10, 9, 8, 7]])
>>> spiral(2,5)
array([[0, 1, 2, 3, 4],
[9, 8, 7, 6, 5]])

Resources