Pseudocode - What is wrong about this - pseudocode

I AM TRYING TO FIND THE ERROR
The code is supposed to find out if a positive integer entered by a user is exactly divisible by the number 3.
n = userinput
WHILE n ≥ 0
n = n - 3
ENDWHILE

You're using greater than OR EQUAL TO so you won't break out of the loop on n = 0, only n = -3 which then triggers your ELSE statement. The EQUAL TO aspect takes you a step too far.
Answering the comment:
Use > instead of >=. Basically the code as written will never allow n to equal 0 at the time the condition is evaluated. Trace each step of the loop using a number like 3.
N = 3
//first pass
WHILE (3 >= 0) // true
n = 3-3 //n now 0
//second pass
WHILE (0 >= 0) //True, 0 is equal to 0
n = 0-3 //n now -3
//third pass
WHILE(-3 >= 0) //False break out of loop
IF(-3 == 0) // false so we jump to the else
ELSE: 3 is not divisible by 3.
One quick way to easily spot check your loops that aren't performing as expected is to just manually run through them with an easy input.

Related

Algorithm to solve for partitions of an Integer

Problem: x1+x2....xn=C where x1,x2....xn >= 0 and is a integer. Find an algorithm that finds every point (x1,x2...xn) that solves this.
Why: I am trying to iterate a multivariable polynomial's terms. The powers of each term can be described by the points above. (You do this operation for C = 0 to C = degree of the polynomial)
I am stuck trying to make an efficient algorithm that produced only the unique solutions (non duplicates) and wanted to see if there is any existing algorithm
After some thought on this problem (and alot of paper), here is my algorithm:
It finds every combination of array of length N that sum to k and the elements are greater then or equal to 0.
This does not do trial and error to get the solution however it does involve quite alot of loops. Greater optimization can be made by creating a generating function when k and n are known beforehand.
If anyone has a better algorithm or finds a problem with this one, please post below, but for now this solves my problem.
Thank you #kcsquared and #Kermit the Frog for leading me in the right direction
""" Function that iterates a n length vector such that the combination sum is always equal to k and all elements are the natural numbers
.Returns if it was stopped or not
Invokes lambda function on every iteration
iteration_lambda (index_vector::Vector{T}, total_iteration::T)::Bool
Return true when it should end
"""
function partition(k::T, n::T, iteration_lambda::Function; max_vector = nothing, sum_vector = nothing, index_vector = nothing)::Bool where T
if n > 0
max_vector = max_vector == nothing ? zeros(T, n) : max_vector
sum_vector = sum_vector == nothing ? zeros(T, n) : sum_vector
index_vector = index_vector == nothing ? zeros(T, n) : index_vector
current_index_index::T = 1
total_iteration::T = 1
max_vector[1] = k
index_vector[1] = max(0, -(k * (n - 1)))
#label reset
if index_vector[current_index_index] <= max_vector[current_index_index]
if current_index_index != n
current_index_index += 1
sum_vector[current_index_index] = sum_vector[current_index_index - 1] + index_vector[current_index_index - 1]
index_vector[current_index_index] = max(0, -(k * (n - current_index_index - 1) + sum_vector[current_index_index]))
max_vector[current_index_index] = k - sum_vector[current_index_index]
else
if iteration_lambda(index_vector, total_iteration)
return true
end
total_iteration += 1
index_vector[end] += 1
end
#goto reset
end
if current_index_index != 1
current_index_index -= 1
index_vector[current_index_index] += 1
#goto reset
end
end
return false
end

Algorithm to sum up all digits of a number

Can you please explain to me how this loop works? What is going on after first loop and after second etc.
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
>>> print sum(123)
6
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
Better rewrite this way (easier to understand):
def sum(n):
s = 0 // start with s = 0
while n > 0: // while our number is bigger than 0
s += n % 10 // add the last digit to s, for example 54%10 = 4
n /= 10 // integer division = just removing last digit, for example 54/10 = 5
return s // return the result
n > 0 in Python can be simply written as n
but I think it is bad practice for beginners
so basically, what we are doing in this algorithm is that we are taking one digit at a time from least significant digit of the number and adding that in our s (which is sum variable), and once we have added the least significant digit, we are then removing it and doing the above thing again and again till the numbers remains to be zero, so how do we know the least significant digit, well just take the remainder of the n by dividing it with 10, now how do we remove the last digit(least significant digit) , we just divide it with 10, so here you go, let me know if it is not understandable.
int main()
{
int t;
cin>>t;
cout<<floor(log10(t)+1);
return 0;
}
Output
254
3

Why does my number only stay at 2 for the Collatz sequence?

I am trying to make a program that calculates when a number will reach zero using the Collatz sequence. Here is my code for that program:
import time
def run(z):
while z != 1:
if isEven(z) == True:
z = z/2
print z
else:
z = (3*z)+1
print z
else:
print 'Got one!'
z = z+1
print 'Trying for %d...' %(z)
time.sleep(0.1)
run(z)
def isEven(number):
return number % 2 == 0
run(z)
However, the z never goes above 2, it only keeps printing:
Got one!
Trying for 2...
1
Got one!
Trying for 2...
1
And so on... Can anyone tell me what I am doing wrong?
The Collatz conjecture is that you will reach one, not zero; when you reach one, you should stop. Also, you have an odd combination of while loop and recursive calling. A very simple recursive implementation:
def collatz(n):
print(n)
if n == 1: # base case
print("Done!")
else:
if n % 2: # odd number
collatz((3 * n) + 1)
else: # even number
collatz(n / 2)
or iterative version:
def collatz(n):
while n != 1:
print(n)
if n % 2: # odd number
n = (3 * n) + 1
else: # even number
n /= 2
print(n)
print("Done!")
If you want to analyse how long a number takes to reach one, you can rejig one of those implementations, e.g.:
def collatz(n):
count = 0
while n != 1:
count += 1
if n % 2: # odd number
n = (3 * n) + 1
else: # even number
n /= 2
return count
You can then call this function, working through the integers, creating the Collatz sequence for each one, for example:
seq_len = [(n, collatz(n)) for n in range(1, 101)]
Once z is 1, you exit the while loop, entering the else, which calls run(2), which sets z back to 1, which calls run(2) and so on and so on.

How to get the target number with +3 or *5 operations without recursion?

This is an interview problem I came across yesterday, I can think of a recursive solution but I wanna know if there's a non-recursive solution.
Given a number N, starting with number 1, you can only multiply the result by 5 or add 3 to the result. If there's no way to get N through this method, return "Can't generate it".
Ex:
Input: 23
Output: (1+3)*5+3
Input: 215
Output: ((1*5+3)*5+3)*5
Input: 12
Output: Can't generate it.
The recursive method can be obvious and intuitive, but are there any non-recursive methods?
I think the quickest, non recursive solution is (for N > 2):
if N mod 3 == 1, it can be generated as 1 + 3*k.
if N mod 3 == 2, it can be generated as 1*5 + 3*k
if N mod 3 == 0, it cannot be generated
The last statement comes from the fact that starting with 1 (= 1 mod 3) you can only reach numbers which are equals to 1 or 2 mod 3:
when you add 3, you don't change the value mod 3
a number equals to 1 mod 3 multiplied by 5 gives a number equals to 2 mod 3
a number equals to 2 mod 3 multiplied by 5 gives a number equals to 1 mod 3
The key here is to work backwards. Start with the number you want to reach and if it's divisible by 5 then divide by 5 because multiplication by 5 results in a shorter solution than addition by 3. The only exceptions are if the value equals 10, because dividing by 5 would yield 2 which is insolvable. If the number is not divisible by 5 or is equal to 10, subtract 3. This produces the shortest string
Repeat until you reach 1
Here is python code:
def f(x):
if x%3 == 0 or x==2:
return "Can't generate it"
l = []
while x!=1:
if x%5 != 0 or x==10:
l.append(3)
x -= 3
else:
l.append(5)
x /=5
l.reverse()
s = '1'
for v in l:
if v == 3:
s += ' + 3'
else:
s = '(' + s + ')*5'
return s
Credit to the previous solutions for determining whether a given number is possible
Model the problem as a graph:
Nodes are numbers
Your root node is 1
Links between nodes are *5 or +3.
Then run Dijkstra's algorithm to get the shortest path. If you exhaust all links from nodes <N without getting to N then you can't generate N. (Alternatively, use #obourgain's answer to decide in advance whether the problem can be solved, and only attempt to work out how to solve the problem if it can be solved.)
So essentially, you enqueue the node (1, null path). You need a dictionary storing {node(i.e. number) => best path found so far for that node}. Then, so long as the queue isn't empty, in each pass of the loop you
Dequeue the head (node,path) from the queue.
If the number of this node is >N, or you've already seen this node before with fewer steps in the path, then don't do any more on this pass.
Add (node => path) to the dictionary.
Enqueue nodes reachable from this node with *5 and +3 (together with the paths that get you to those nodes)
When the loop terminates, look up N in the dictionary to get the path, or output "Can't generate it".
Edit: note, this is really Breadth-first search rather than Dijkstra's algorithm, as the cost of traversing a link is fixed at 1.
You can use the following recursion (which is indeed intuitive):
f(input) = f(input/5) OR f(input -3)
base:
f(1) = true
f(x) = false x is not natural positive number
Note that it can be done using Dynamic Programming as well:
f[-2] = f[-1] = f[0] = false
f[1] = true
for i from 2 to n:
f[i] = f[i-3] or (i%5 == 0? f[i/5] : false)
To get the score, you need to get on the table after building it from f[n] and follow the valid true moves.
Time and space complexity of the DP solution is O(n) [pseudo-polynomial]
All recursive algorithms can also be implemented using a stack. So, something like this:
bool canProduce(int target){
Stack<int> numStack;
int current;
numStack.push(1);
while(!numStack.empty){
current=numStack.top();
numStack.pop();
if(current==target)
return true;
if(current+3 < target)
numStack.push(current+3);
if(current*5 < target)
numStack.push(current*5);
}
return false;
}
In Python:
The smart solution:
def f(n):
if n % 3 == 1:
print '1' + '+3' * (n // 3)
elif n % 3 == 2:
print '1*5' + '+3' * ((n - 5) // 3)
else:
print "Can't generate it."
A naive but still O(n) version:
def f(n):
d={1:'1'}
for i in range(n):
if i in d:
d[i*5] = '(' + d[i] + ')*5'
d[i+3] = d[i] + '+3'
if n in d:
print d[n]
else:
print "Can't generate it."
And of course, you could also use a stack to reproduce the behavior of the recursive calls.
Which gives:
>>> f(23)
(1)*5+3+3+3+3+3+3
>>> f(215)
(1)*5+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3+3
>>> f(12)
Can't generate it.

Find the minimum number of operations required to compute a number using a specified range of numbers

Let me start with an example -
I have a range of numbers from 1 to 9. And let's say the target number that I want is 29.
In this case the minimum number of operations that are required would be (9*3)+2 = 2 operations. Similarly for 18 the minimum number of operations is 1 (9*2=18).
I can use any of the 4 arithmetic operators - +, -, / and *.
How can I programmatically find out the minimum number of operations required?
Thanks in advance for any help provided.
clarification: integers only, no decimals allowed mid-calculation. i.e. the following is not valid (from comments below): ((9/2) + 1) * 4 == 22
I must admit I didn't think about this thoroughly, but for my purpose it doesn't matter if decimal numbers appear mid-calculation. ((9/2) + 1) * 4 == 22 is valid. Sorry for the confusion.
For the special case where set Y = [1..9] and n > 0:
n <= 9 : 0 operations
n <=18 : 1 operation (+)
otherwise : Remove any divisor found in Y. If this is not enough, do a recursion on the remainder for all offsets -9 .. +9. Offset 0 can be skipped as it has already been tried.
Notice how division is not needed in this case. For other Y this does not hold.
This algorithm is exponential in log(n). The exact analysis is a job for somebody with more knowledge about algebra than I.
For more speed, add pruning to eliminate some of the search for larger numbers.
Sample code:
def findop(n, maxlen=9999):
# Return a short postfix list of numbers and operations
# Simple solution to small numbers
if n<=9: return [n]
if n<=18: return [9,n-9,'+']
# Find direct multiply
x = divlist(n)
if len(x) > 1:
mults = len(x)-1
x[-1:] = findop(x[-1], maxlen-2*mults)
x.extend(['*'] * mults)
return x
shortest = 0
for o in range(1,10) + range(-1,-10,-1):
x = divlist(n-o)
if len(x) == 1: continue
mults = len(x)-1
# We spent len(divlist) + mults + 2 fields for offset.
# The last number is expanded by the recursion, so it doesn't count.
recursion_maxlen = maxlen - len(x) - mults - 2 + 1
if recursion_maxlen < 1: continue
x[-1:] = findop(x[-1], recursion_maxlen)
x.extend(['*'] * mults)
if o > 0:
x.extend([o, '+'])
else:
x.extend([-o, '-'])
if shortest == 0 or len(x) < shortest:
shortest = len(x)
maxlen = shortest - 1
solution = x[:]
if shortest == 0:
# Fake solution, it will be discarded
return '#' * (maxlen+1)
return solution
def divlist(n):
l = []
for d in range(9,1,-1):
while n%d == 0:
l.append(d)
n = n/d
if n>1: l.append(n)
return l
The basic idea is to test all possibilities with k operations, for k starting from 0. Imagine you create a tree of height k that branches for every possible new operation with operand (4*9 branches per level). You need to traverse and evaluate the leaves of the tree for each k before moving to the next k.
I didn't test this pseudo-code:
for every k from 0 to infinity
for every n from 1 to 9
if compute(n,0,k):
return k
boolean compute(n,j,k):
if (j == k):
return (n == target)
else:
for each operator in {+,-,*,/}:
for every i from 1 to 9:
if compute((n operator i),j+1,k):
return true
return false
It doesn't take into account arithmetic operators precedence and braces, that would require some rework.
Really cool question :)
Notice that you can start from the end! From your example (9*3)+2 = 29 is equivalent to saying (29-2)/3=9. That way we can avoid the double loop in cyborg's answer. This suggests the following algorithm for set Y and result r:
nextleaves = {r}
nops = 0
while(true):
nops = nops+1
leaves = nextleaves
nextleaves = {}
for leaf in leaves:
for y in Y:
if (leaf+y) or (leaf-y) or (leaf*y) or (leaf/y) is in X:
return(nops)
else:
add (leaf+y) and (leaf-y) and (leaf*y) and (leaf/y) to nextleaves
This is the basic idea, performance can be certainly be improved, for instance by avoiding "backtracks", such as r+a-a or r*a*b/a.
I guess my idea is similar to the one of Peer Sommerlund:
For big numbers, you advance fast, by multiplication with big ciphers.
Is Y=29 prime? If not, divide it by the maximum divider of (2 to 9).
Else you could subtract a number, to reach a dividable number. 27 is fine, since it is dividable by 9, so
(29-2)/9=3 =>
3*9+2 = 29
So maybe - I didn't think about this to the end: Search the next divisible by 9 number below Y. If you don't reach a number which is a digit, repeat.
The formula is the steps reversed.
(I'll try it for some numbers. :) )
I tried with 2551, which is
echo $((((3*9+4)*9+4)*9+4))
But I didn't test every intermediate result whether it is prime.
But
echo $((8*8*8*5-9))
is 2 operations less. Maybe I can investigate this later.

Resources