Digit sum in Prolog - numbers

How can I define in Prolog the rule to calculate the digit sum of an integer?
Example:
digitsum[Integer, Result] :- ...
so that the query digitsum(123, X). results in X = 6 (=1+2+3). A solution running under SWI-Prolog is appreciated.

This problem naturally leads to an implementation using library(clpfd):
:- use_module(library(clpfd)).
digitsum(Z,S) :-
Z #= 0,
S #= 0.
digitsum(Z0, S0) :-
Z0 #> 0, S0 #> 0,
S0 #= Z0 mod 10 + S1,
Z1 #= Z0 // 10, % should be rather div
digitsum(Z1, S1).
?- digitsum(D,S).
D = S, S = 0
; D = S, S in 1..9
; D in 10..99, D/10#=_A, D mod 10#=_B,
_A in 1..9, _B+_A#=S, _B in 0..9, S in 1..18
; ... .
The first answer is about zero. The second says that a number 1..9 is the same as its sum.
Then it talks about the numbers 10..99 etc.

Related

How to perform Modulo greatest common divisor?

Suppose that gcd(e,m) = g. Find integer d such that (e x d) = g mod m
Where m and e are greater than or equal to 1.
The following problem seems to be solvable algebraically but I've tried doing it and it give me an integer number. Sometimes, the solution for d is an integer and sometimes it isn't. How can I approach this problem?
d can be computed with the extended euklidean algorithm, see e.g. here:
https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
The a,b on that page are your e,m, and your d will be the x.
Perhaps you are assuming that both e and m are integers, but the problem allows them to be non-integers? There is only one case that gives an integer solution when both e and m are integers.
Why strictly integer output is not a reasonable outcome if e != m:
When you look at a fraction like 3/7 say, and refer to its denominator as the numerator's "divisor", this is a loose sense of the word from a classical math-y perspective. When you talk about the gcd (greatest common divisor), the "d" refers to an integer that divides the numerator (an integer) evenly, resulting in another integer: 4 is a divisor of 8, because 8/4 = 2 and 2 is an integer. A computer science or discrete mathematics perspective might frame a divisor as a number d that for a given number a gives 0 when we take a % d (a mod d for discrete math). Can you see that the absolute value of a divisor can't exceed the absolute value of the numerator? If it did, you would get pieces of pie, instead of whole pies - example:
4 % a = 0 for a in Z (Z being the set of integers) while |a| <= 4 (in math-y notation, that set is: {a ∈ Z : |a| <= 4}), but
4 % a != 0 for a in Z while |a| > 4 (math-y: {a ∈ Z : |a| > 4}
), because when we divide 4 by stuff bigger than it, like 5, we get fractions (i.e. |4/a| < 1 when |a| > 4). Don't worry too much about the absolute value stuff if it throws you off - it is there to account for working with negative numbers since they are integers as well.
So, even the "greatest" of divisors for any given integer will be smaller than the integer. Otherwise it's not a divisor (see above, or Wikipedia on divisors).
Look at gcd(e, m) = g:
By the definition of % (mod for math people), for any two numbers number1 and number2, number1 % number2 never makes number1 bigger: number1 % number2 <= number1.
So substitute: (e * d) = g % m --> (e * d) <= g
By the paragraphs above and definition of gcd being a divisor of both e and m: g <= e, m.
To make (e * d) <= g such that d, g are both integers, knowing that g <= e since g is a divisor of e, we have to make the left side smaller to match g. You can only make an integer smaller with multiplcation if the other multipland is 0 or a fraction. The problem specifies that d is an integer, so we one case that works - the d = 0 case - and infinitely many that give a contradiction - contradiction that e, m, and d all be integers.
If e == m:
This is the d = 0 case:
If e == m, then gcd(e, m) = e = m - example: greatest common divisor of 3 and 3 is 3
Then (e * d) = g % m is (e * d) = m % m and m % m = 0 so (e * d) = 0 implying d = 0
How to code a function that will find d when either of e or m might be NON-integer:
A lot of divisor problems are done iteratively, like "find the gcd" or "find a prime number". That works in part because those problems deal strictly with integers, which are countable. With this problem, we need to allow e or m to be non-integer in order to have a solution for cases other than e = m. The set of rational numbers is NOT countable, however, so an iterative solution would eventually make your program crash. With this problem, you really just want a formula, and possibly some cases. You might set it up like this:
If e == m
return 0 # since (e * d) = m % m -> d = 0
Else
return g / e
Lastly:
Another thing that might be useful depending on what you do with this problem is the fact that the right-hand-side is always either g or 0, because g <= m since g is a divisor of m (see all the stuff above). In the cases where g < m, g % m = g. In the case where g == m, g % m = 0.
The #asp answer with the link to the Wikipedia page on the Euclidean Algorithm is good.
The #aidenhjj comment about trying the math-specific version of StackOverflow is good.
In case this is for a math class and you aren't used to coding: <=, >=, ==, and != are computer speak for ≤, ≥, "are equal", and "not equal" respectively.
Good luck.

Evaluation of a polynomial in SciLab

Could you please help me find a mistake in my code?
I need to calculate the polynomial, with parameters the vector and the value of the variable.
I am not allowed to use the power sign (^)
I have got this code but it doesn't work and I don't see what I am doing wrong.
function f=veelTermEvaluatie(V,x)
f=V(1);
for i=2:length(V)
for j=0:i-1
if j=0 then x=x
else x=x*x
end
f=V(i)*x
end
end
endfunction
V=[1 2 3 4 5 6]
x=3
I first refactored your code, to remove the j=0 situation, since this does not change anything since x=x it can be skipped by starting at j=1. I also added some debug printing :
function f=veelTermEvaluatie(V,x)
f=V(1);
for i=2:length(V)
printf("\nI: %d --> ", i)
for j=1:i-1
x = x * x
printf("j: %d, x=%d ",j,x)
end
f=V(i)*x
end
return f
endfunction
After that it became clear that you multiply the same x, each and every time:
I: 2 --> j: 1, x=9
I: 3 --> j: 1, x=81 j: 2, x=6561
I: 4 --> j: 1, x=43046721 j: 2, x=-501334399 j: 3, x=0
I: 5 --> j: 1, x=0 j: 2, x=0 j: 3, x=0 j: 4, x=Inf
I: 6 --> j: 1, x=Inf j: 2, x=Inf j: 3, x=Inf j: 4, x=Inf j: 5, x=Inf
What also happens is that you update the value of f to the highest term, disregarding any other terms.
I think your meaning is to return all terms
So you should create a local x which is reset for every term.
Working example
function f=veelTermEvaluatie(V,x)
//Initialize the result to be a copy of the input
f=V;
// For each element in the input (except the first)
for i=2:length(V)
printf("\nI: %d --> ", i);
//Initialize a local x variable to the global x
new_x = x;
for j=1:i-1
// Update only the local x
new_x = new_x * x;
printf("j: %d, x=%d ",j,x);
end
// Multiply the value in the array with the local x value
f(i)=V(i)*new_x;
end
return f
endfunction
V=[1 2 3 4 5 6]
x=3
result = veelTermEvaluatie(V,x)
disp(result)
disp(sum(result))
Scilab has already a horner function so you don't need to reinvent the wheel. For example, to evaluate the polynomial 1+2*x+4*x^2+8*x^3 at x=-1,0,1 you can proceed as follows:
p = poly([1 2 4 8],'x','coeff')
pval = horner(p,[-1 0 1])
which yields the following output
--> p = poly([1 2 4 8],'x','coeff')
p =
2 3
1 +2x +4x +8x
--> pval = horner(p,[-1 0 1])
pval =
-5. 1. 15.
What you should do is implement the Horner scheme.
f=V(n)
for i from n-1 down to 0 do
f = f*x
f = f+V(i)
end for
return f
In the question, you return the array of values V(i)*x^(2^i), in the previous answer, the array of evaluated terms V(i)*x^i is returned, but the value of the polynomial is the sum over those terms.
Please elaborate on the input format. Is V an array with index range 1:n? What is the intended relation between index and degree?

How can I simplify in Matlab?

I want to simplify the following operation, but it yields me an error that says: too many input arguments. Can anybody tell me what am i doing wrong???
>>
syms a b c d e f g h i j k l x y xy
A=[1 a b a^2 a*b b^2; 1 c d c*2 c*d d^2; 1 e f e^2 e*f f^2; 1 g h g^2 g*h h^2; 1 i j i^2 i*j j^2; 1 k l k^2 k*l l^2]
B=[1; 0; 0; 0; 0; 0]
A =
[ 1, a, b, a^2, a*b, b^2]
[ 1, c, d, 2*c, c*d, d^2]
[ 1, e, f, e^2, e*f, f^2]
[ 1, g, h, g^2, g*h, h^2]
[ 1, i, j, i^2, i*j, j^2]
[ 1, k, l, k^2, k*l, l^2]
B =
1
0
0
0
0
0
>> simplify(inv(A)*B, 'steps', 100)enter code here
I've put the code you pasted in my copy of matlab (R2013a) and it finishes without any errors. The result is not simplified very much though.
If your computer is choking on the computation (it is very long), you could try separating the things a bit and see if it helps.
vec=inv(A)*B
for n=1:6
results(n)=simplify(vec(n), 'steps', 100);
end
results
Your call belongs to this MATLAB function:
But it is in Symbolic Math Toolbox, which means it can only simplify math formulas instead of complex matrix computation.
Simplify Favoring Real Numbers
To force simplify favor real values over complex values, set the value of Criterion to preferReal:
syms x
f = (exp(x + exp(-x*i)/2 - exp(x*i)/2)*i)/2 - (exp(- x - exp(-x*i)/2 + exp(x*i)/2)*i)/2;
simplify(f, 'Criterion','preferReal', 'Steps', 100)
ans =
cos(sin(x))*sinh(x)*i + sin(sin(x))*cosh(x)
If x is a real value, then this form of expression explicitly shows the real and imaginary parts.
Although the result returned by simplify with the default setting for Criterion is shorter, here the complex value is a parameter of the sine function:
simplify(f, 'Steps', 100)
ans =
sin(x*i + sin(x))
Instead, I think you could try use this function:
Simplify(f, Steps = numberOfSteps)
But first of all, you need a 'f' which could be used like a recursion or iteration function.
e.g. Simplify(sin(x)^2 + cos(x)^2, All)
Hope this helps!

Modulo and remainder (Chinese remainder theorem) in MATLAB

How do I find the least possible value in Matlab, given the modulo values and its remainder values in an array? for example:
A=[ 23 90 56 36] %# the modulo values
B=[ 1 3 37 21] %# the remainder values
which leads to the answer 93; which is the least possible value.
EDIT:
Here is my code but it only seems to display the last value of the remainder array as the least value:
z = input('z=');
r = input('r=');
c = 0;
m = max(z);
[x, y] = find(z == m);
r = r(y);
f = find(z);
q = max(f);
p = z(1:q);
n = m * c + r;
if (mod(n, p) == r)
c = c + 1;
end
fprintf('The lowest value is %0.f\n', n)
Okay, so your goal is to find the smallest x that satisfies B(i) = mod(x, A(i)) for each i.
This page contains a very simple (yet thorough) explanation of how to solve your set of equations using the Chinese Remainder Theorem. So, here's an implementation of the described method in MATLAB:
A = [23, 90]; %# Moduli
B = [1, 3]; %# Remainders
%# Find the smallest x that satisfies B(i) = mod(x, A(i)) for each i
AA = meshgrid(A);
assert(~sum(sum(gcd(AA, AA') - diag(A) > 1))) %# Check that moduli are coprime
M = prod(AA' - diag(A - 1));
[G, U, V] = gcd(A, M);
x = mod(sum(B .* M .* V), prod(A))
x =
93
You should note that this algorithm works only for moduli (the values of A) which are coprime!
In your example, they are not, so this will not work for your example (I've put an assert command to break the script if the moduli are not coprime). You should try to implement yourself the full solution for non-comprime moduli!
P.S
Also note that the gcd command uses Euclid's algorithm. If you are required to implement it yourself, this and this might serve you as good references.

Matlab Generating a Matrix

I am trying to generate a matrix in matlab which I will use to solve a polynomial regression formula.
Here is how I am trying to generate the matrix:
I have an input vector X containing N elements and an integer d. d is the integer to know how many times we will add a new column to the matrix we are trying to generate int he following way.
N = [X^d X^{d-1} ... X^2 X O]
O is a vector of same length as X with all 1's.
Everytime d > 2 it does not work.
Can you see any errors in my code (i am new to matlab):
function [ PR ] = PolyRegress( X, Y, d )
O = ones(length(X), 1)
N = [X O]
for j = 2:d
tmp = power(X, j)
N = [tmp N]
end
%TO DO: compute PR
end
It looks like the matlab function vander already does what you want to do.
The VANDER function will only generate powers of the vector upto d = length(X)-1. For a more general solution, you can use the BSXFUN function (works with any value of d):
N = bsxfun(#power, X(:), d:-1:0)
Example:
>> X = (1:.5:2);
>> d = 5;
>> N = bsxfun(#power, X(:), d:-1:0)
N =
1 1 1 1 1 1
7.5938 5.0625 3.375 2.25 1.5 1
32 16 8 4 2 1
I'm not sure if this is the order you want, but it can be easily reversed: use 0:d instead of d:-1:0...