Removing Cyclotomic Factors from a Polynomial - Pari - polynomials

I want to take some polynomial f and remove all of it's cyclotomic factors, and then look at the resulting polynomial (say g). I'm aware of polcyclofactors and the current code I have tried is:
c(f)=polcyclofactors(f)
p(f)=prod(i=1,#c(f),c(f)[i])
g(f)=f/p(f)
The issue I have is that polcyclofactors doesn't take into account multiplicity of the cyclotomic factors. For example:
f=3*x^4 + 8*x^3 + 6*x^2 - 1
g(f)
= 3*x^3 + 5*x^2 + x - 1
But
factor(f)
=
[ x + 1 3]
[3*x - 1 1]
Is there any way to be able to nicely include multiple cyclotomic factors of f to divide by? Or will I have to look at factorising f and try and removing cyclotomic factors that way?

The following two suggestions are based on repeating the divisions until no more can be done (they are both very similar).
Suggestion 1:
r(f)={my(c); while(c=polcyclofactors(f); #c, f=f/vecprod(c)); f}
Suggestion 2:
r(f)={my(g=vecprod(polcyclofactors(f))); while(poldegree(g), f=f/g; g=gcd(f,g)); f}
Another suggestion without a loop:
r(f)={my(g=vecprod(polcyclofactors(f))); numerator(f/g^(poldegree(f)))}
Now a version that is probably superior: For each factor valuation can be used to get the required power.
r(f)={f/vecprod([t^valuation(f,t) | t<-polcyclofactors(f)])}

Related

Sympy : powsimp does not work on a simple example

Trying to solve my problem (Sympy : How is it possible to simplify power of sum?), I found a simple example where powsimp does not work.
In this case, the power simplification is done
x,y,n=sp.symbols("x y n",positive=True,real=True)
expr=sp.Pow(x,n)*sp.Pow(y,-n)
expr.powsimp()
But not in this case :
expr=sp.Pow(x,n+1)*sp.Pow(y,-n-1)
expr.powsimp()
Is it possible to do power simplification when the exponent is an expression (real and positive of course) ?
powsimp should look for such cases, but until then, converting the exponent to a single variable (and subs will work out the relationship for you for the negated case):
>>> expr
x**(n + 1)*y**(-n - 1)
>>> powsimp(expr.subs(n + 1, var('z',positive=1))).subs(z, n + 1)
(x/y)**(n + 1)

How do I get imaginary numbers without using cmath when calculating the quadratic equation?

I'm currently having trouble understanding how to make imaginary numbers appear when I'm doing the quadratic equation. My assignment is to make the quadratic equation, and get imaginary numbers but I'm having an extremely difficult time getting there.
any help you can offer would be great!
Here is the code i currently have:
import math
print "Hello, please insert 3 numbers to insert into the quadratic equation."
a = input("Please enter the first value: ")
b = input("Please enter the second value: ")
c = input("Please enter the third value: ")
rootValue = b**2 - 4*a*c
if rootValue < 0:
print (-b-(rootValue)**(.5)) / (2 * a)
if rootValue > 0:
print ((-b + (rootValue)**(1/2)) /(2 * a))
if rootValue == 0:
print -b/(2*a)
please help!!! i'm so stuck right now.
I think you have to do something with the problem if rootValue < 0; but I'm not sure how to do that.
I'm also not allowed to use 'import cmath', I'm supposed to make it so that you can just do this this way.
There are a couple of problems with your code besides how to represent complex numbers. Remember that if rootValue <> 0, there are ALWAY TWO roots:
(-b +/- sqrt(rootValue)/ 2a
It doesn't matter if the rootValue is positive or negative, there's still two roots. You are branching and only providing one of the two roots in each case. No need for the first two if statements
To make rootValue complex, so that you can have complex result when you take the square root, either set it equal to complex(b2 - 4*a*c, 0) or to (b2 - 4*a*c, 0) + 0j.
You want to raise things to the 0.5 power for each of the two roots, NOT the (1/2) power, as you've done in one statement
For completeness, you may want to deal with the a = 0 case.
If you still have problems, let us know.

Solving a linear equation in one variable

What would be the most efficient algorithm to solve a linear equation in one variable given as a string input to a function? For example, for input string:
"x + 9 – 2 - 4 + x = – x + 5 – 1 + 3 – x"
The output should be 1.
I am considering using a stack and pushing each string token onto it as I encounter spaces in the string. If the input was in polish notation then it would have been easier to pop numbers off the stack to get to a result, but I am not sure what approach to take here.
It is an interview question.
Solving the linear equation is (I hope) extremely easy for you once you've worked out the coefficients a and b in the equation a * x + b = 0.
So, the difficult part of the problem is parsing the expression and "evaluating" it to find the coefficients. Your example expression is extremely simple, it uses only the operators unary -, binary -, binary +. And =, which you could handle specially.
It is not clear from the question whether the solution should also handle expressions involving binary * and /, or parentheses. I'm wondering whether the interview question is intended:
to make you write some simple code, or
to make you ask what the real scope of the problem is before you write anything.
Both are important skills :-)
It could even be that the question is intended:
to separate those with lots of experience writing parsers (who will solve it as fast as they can write/type) from those with none (who might struggle to solve it at all within a few minutes, at least without some hints).
Anyway, to allow for future more complicated requirements, there are two common approaches to parsing arithmetic expressions: recursive descent or Dijkstra's shunting-yard algorithm. You can look these up, and if you only need the simple expressions in version 1.0 then you can use a simplified form of Dijkstra's algorithm. Then once you've parsed the expression, you need to evaluate it: use values that are linear expressions in x and interpret = as an operator with lowest possible precedence that means "subtract". The result is a linear expression in x that is equal to 0.
If you don't need complicated expressions then you can evaluate that simple example pretty much directly from left-to-right once you've tokenised it[*]:
x
x + 9
// set the "we've found minus sign" bit to negate the first thing that follows
x + 7 // and clear the negative bit
x + 3
2 * x + 3
// set the "we've found the equals sign" bit to negate everything that follows
3 * x + 3
3 * x - 2
3 * x - 1
3 * x - 4
4 * x - 4
Finally, solve a * x + b = 0 as x = - b/a.
[*] example tokenisation code, in Python:
acc = None
for idx, ch in enumerate(input):
if ch in '1234567890':
if acc is None: acc = 0
acc = 10 * acc + int(ch)
continue
if acc != None:
yield acc
acc = None
if ch in '+-=x':
yield ch
elif ch == ' ':
pass
else:
raise ValueError('illegal character "%s" at %d' % (ch, idx))
Alternative example tokenisation code, also in Python, assuming there will always be spaces between tokens as in the example. This leaves token validation to the parser:
return input.split()
ok some simple psuedo code that you could use to solve this problem
function(stinrgToParse){
arrayoftokens = stringToParse.match(RegexMatching);
foreach(arrayoftokens as token)
{
//now step through the tokens and determine what they are
//and store the neccesary information.
}
//Use the above information to do the arithmetic.
//count the number of times a variable appears positive and negative
//do the arithmetic.
//add up the numbers both positive and negative.
//return the result.
}
The first thing is to parse the string, to identify the various tokens (numbers, variables and operators), so that an expression tree can be formed by giving operator proper precedences.
Regular expressions can help, but that's not the only method (grammar parsers like boost::spirit are good too, and you can even run your own: its all a "find and recourse").
The tree can then be manipulated reducing the nodes executing those operation that deals with constants and by grouping variables related operations, executing them accordingly.
This goes on recursively until you remain with a variable related node and a constant node.
At the point the solution is calculated trivially.
They are basically the same principles that leads to the production of an interpreter or a compiler.
Consider:
from operator import add, sub
def ab(expr):
a, b, op = 0, 0, add
for t in expr.split():
if t == '+': op = add
elif t == '-': op = sub
elif t == 'x': a = op(a, 1)
else : b = op(b, int(t))
return a, b
Given an expression like 1 + x - 2 - x... this converts it to a canonical form ax+b and returns a pair of coefficients (a,b).
Now, let's obtain the coefficients from both parts of the equation:
le, ri = equation.split('=')
a1, b1 = ab(le)
a2, b2 = ab(ri)
and finally solve the trivial equation a1*x + b1 = a2*x + b2:
x = (b2 - b1) / (a1 - a2)
Of course, this only solves this particular example, without operator precedence or parentheses. To support the latter you'll need a parser, presumable a recursive descent one, which would be simper to code by hand.

implement DP for a recursive function

I have the following recursive function:
typedef unsigned long long ull;
ull calc(ull b, ull e)
{
if (!b) return e;
if (!e) return b;
return calc(b - 1, e - 1) + calc(b - 1, e) - calc(b, e - 1);
}
I want to implement it with dynamic programming (i.e. using storage). I have tried to use a map<pair<ull, ull>, ull> but it is too slow also. I couldn't implement it using arrays O(1) too.
I want to find a solution so that this function solves quickly for large b, es.
Make a table b/e and fill it cell by cell. This is DP with space and time complexity O(MaxB*MaxE).
Space complexity may be reduced with Ante's proposal in comment - store only two needed rows or columns.
0 1 2 3 4 5
1 0 3 . . .
2 . . . . .
3 . . . . .
4 . . . . .
If a bottom up representation is what you want then this would do fine.
Fill up the table as MBo has shown
This can be done as:
for e from 0 to n:
DP[0][e] = e
for b from 0 to n:
DP[b][0] = b
for i from 1 to n:
for j from 1 to n:
DP[i][j] = DP[i-1][j-1] + DP[i-1][j] - DP[i][j-1]
now your answer for any b,e is simply DP[b][e]
You might want to take a look at this recent blog posting on general purpose automatic memoization. The author discusses various data structures, such std::map, std::unordered_map etc. Warning: uses template-heavy code.
You can implement in O(n^2) (assuming n as max number of values for b and e ) by using a 2 dimensional array. Each current value for i,j would depend on the value at i-1,j and i-1,j-1 and i,j-1. Make sure you handle cases for i=0, j=0.

Solve an equation containing three unknown prime numbers [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I was recently asked a question in an interview & have been unable to crack it, after my own efforts have failed & Google not showing any results , I am posting it here so that anyone else may also try their hand on it .
Given the equation:
a (a + b) = c - 120
where a,b & c are unequal prime numbers, find a, b & c.
I know I must use some property of the prime numbers to reduce the problem to a simpler one, but I can't think of one. Any suggestions/solutions will be appreciated.
The best I could come up with is that :
There may be multiple solutions to it. My first approach was a brute force search for 3 prime numbers that solved this equations. (I know , totally useless)
The second approach was a refinement of the first, to modify the equation to a (a + b) - 120 = c. So now we reduce our brute force variables to just a & b & check if the LHS is prime no for the selected a & b. (If c were to be large, finding out whether the LHS is a prime would take away the advantage gained by reducing the variables from 3 to 2.)
So you see, I am not really going anywhere.
all primes are odd, except 2 - (1)
all primes are positive - (2)
odd - even = odd (3)
(1), (2) => c > 120 and c is odd - (4)
odd * odd = odd - (5)
(3), (4), (5) => c-120 is odd => a(a+b) is odd - (6)
even + odd = odd - (7)
(6) => a is odd, a+b is odd (8)
(7), (8) => b is even => b = 2
So, we have a^2 + 2a = c-120
I couldn't go any further
Let's stipulate that c > 120. That implies c != 2. So the RHS is odd.
Therefore the LHS has to be odd, so a (a + b) has to be odd. So a is odd, and a+b is odd. This only works out if b is even, and b is prime, so b = 2.
So we have a(a+2) = c - 120.
So a^2 + 2a + (120-c) = 0
Using the quadratic formula, solving for a, we get
[-2 +- sqrt(2^2 - 4 * 1 * (120 - c))] / 2
= -1 +- sqrt(1 - (120-c))
= -1 + sqrt(c - 119)
So we need a prime number c, so that c - 119 is a perfect square.
This is a quick calculation with a table of primes.
The smallest one I can find is c = 263, so a = 11, b = 2
It looks like c=443, a=17, b=2 also works.
There don't appear to be any other c values below 1000.
Possibly there are many, many others.