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.
Related
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)])}
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.
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.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Question: input an int number ex: ABCD, verify that is ABCD = AB*CD or not
(note that we don't how many digits this number got, just know it is an positive integer
and yes, it the number of digits is odd we can conclude result is No, immediately by... eye lol)
for example:
Enter a number: 88
Output: No
Enter a number: 12600
Output: No
Enter a number: 116725
Output: Yes, 116 * 725 = 116725 (**this is just example,
not actual result, just help to understand how output look like**)
Problem is that, you can't use array, jump and bitwise in order to solve this. Yes, if we can use array then not much to say, put input number in an array, check first half multiply other half....bla..bla... I need help with IDEA without using array to solve this problem, right now I'm stuck! Thank you guy very much!
Your program can safely output No for every input. Proof:
You are looking for integers A and B such that A*B = A*10^k + B, with A and B > 0 and B < 10^k.
If A*B = A*10^k + B, then B = 10^k + B/A > 10^k. But B had to be less than 10^k, so this is a contradiction. Therefore no such A and B exist.
A longer proof:
You are looking for integers A and B such that A*B = A*10^k + B, with A and B > 0 and B < 10^k.
Subtract B from both sides to get (A-1)*B = A*10^k.
Since A is a factor in the right hand side it is also a factor in the left hand side. But A and A-1 are coprime, so A must divide B. So, B = n*A for some integer n.
Now we have A*B = A*10^k + n*A, or A*B = (10^k + n)*A. Since A > 0 we can divide both sides by A to get B = 10^k+n. But this is impossible since B was supposed to be less than 10^k!
A little hint to your 6 digits number:
to get last 3 digits use % 1000
to get first 3 digits use (int) X/1000.
Notice that 1000 == 10^3.
Write a program that asks for the input and then prints "No".
Done.
It's not too clear what you're trying to do. ABCD == AB*CD suggests
four digit numbers. For a four digit number x, a test for the above
would be x == (x / 100) * (x % 100). For a six digit number, replace
100 with 1000, and more generally, for an n digit number, where
n is even, use 10^(n/2). If n is odd, however, I'm not sure what you're looking for, and the last example you give doesn't meet the criteria you mention; if you can permutate the digits in each half, the problem then becomes more complex.
You can read a string, split it in the middle and convert the both parts to an int.
You could also read an int, calculate the number of digits (writing your own loop or using the log function) and split the int after the calculated number of digits.
You can also write a loop that is taking an int ABCD, splitting it into ABC and D and moving the digits from ABC to D while the both have not the same number of digits (you do not need to calculate the number of digits here, there is a quite easy comparison you can do).
To get the number of digits, count how many times you had to divide the number by 10 until it gets smaller than 1.
For 116725, you would need to divide by 10 six times. After that you can print no if the number is odd or calculate the result like James Kanze and ProblemFactory described.
Here's a complete "C/C++" solution:
#include <stdio.h>
int main(void) {
while (fgetc(stdin) != '\n');
return puts("No.");
}
I'm studying for a Discrete Mathematics test and I found this exercise which I can't figure out.
"Build a basic finite automaton (DFA,NFA,NFA-lambda) for the language in the alphabet Sigma = {0,1,2} where the sum of the elements in the string is even AND this sum is more than 3"
I have tried using Kleene's Theorem concatenating two languages like concatenating the one associated with this regular expression:
(00 U 11 U 22 U 02 U 20)* - the even elements
with this one
(22 U 1111 U 222 U 2222)* - the ones whose sum is greater than 3
Does this make any sense?? I think my regex are flabby.
I find your notation a bit fuzzy, so perhaps I'm completely misunderstanding. If so, disregard the following. It seems you're not there yet:
I assume the * means '0 or more times'. However, one of the strings with sum >= 3 must occur. It's say you need a + ('1 or more times').
112 and 211 are missing in the list of strings with sum >= 3.
222 and 2222 in that list are superfluous.
All of these strings may be arbitraryly interspersed with 0s.
The sum of 00 is no more even than the sum of 0.
Edit: how about this (acc is the only accepting state, dot-source):
automaton http://student.science.uva.nl/~sschroev/so/885411.png
At states a and c the string sum is always odd. At states start, b and acc the sum is always even. Furthermore, at start the sum is 0, at b it is 2 and at d it is >= 4. This can be proved rather easily. Hence the accepting state acc meets all criteria.
Edit 2: I'd say this is a regex which accepts the requested language:
0*(2|(1(0|2)*1))(0*(2|(1(0|2)*1))+
Not sure if this is answering your question, but: do you need to submit a regular expression? or will an FSM do?
At any rate, it might be helpful to draw the FSM first, and I think this is a correct DFA:
FSM http://img254.imageshack.us/img254/5324/fsm.png
If that is the case, when constructing your regular expression (which, remember, has different syntax than programming "regex"):
0* to indicate "0 as many times as you want". This makes sense, since 0 in your string doesn't change the state of the machine. (See, in the FSM, 0 just loops back to itself)
You'd need to account for the different combinations of "112" or "22" etc - until you reach at least 4 in your sum.
If your sum is greater than 3, and even, then (0|2)* would keep you at a final state. Otherwise (sum > 3, and odd) you'd need something like 1(0|2)* in order to put you at an accepting state.
(don't know if this helps, or if its right - but it might be a start!)
Each expression, as guided by Stephan, may be:
(0*U 2* U 11)* - the even sums
with this one
(22 U 11 U 222 U 112 U 211 U 121)+ - the ones whose sum is greater than 3
I don't know if it could be simplfied more, it would help designing the automaton.
I find it easier just to think in terms of states. Use five states: 0, 1, 2, EVEN, ODD
Transitions:
State, Input -> New State
(0, 0) -> 0
(0, 1) -> 1
(0, 2) -> 2
(1, 0) -> 1
(1, 1) -> 2
(1, 2) -> ODD
(2, 0) -> 2
(2, 1) -> ODD
(2, 2) -> EVEN
(ODD, 0) -> ODD
(ODD, 1) -> EVEN
(ODD, 2) -> ODD
(EVEN, 0) -> EVEN
(EVEN, 1) -> ODD
(EVEN, 2) -> EVEN
Only EVEN is an accepting state.