Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I wanted to make a greatest common divisor counter in python, but I'm not exactly sure how to go at it, or where to start... Pretty much all I've got is this equation (a and b are numbers):
a = b * quotient + remainder
And I want the counter to print all the steps until remainder is lower than a, and then show the GCD.
I've also searched some more and found out that quotient of 2 numbers can be simply done with the // command and remainder with % command, so basically:
a = b * (a // b) + (a % b)
I'm also aware that I need a loop for the counter, but I've got no idea how to go about that... Help would be most appreciated.
I've seen some codes for GCD, but couldn't find one that would show all the steps.
def gcd_steps(a, b):
steps = []
# this is the standard GCD finding algorithm;
# we simply amend it with "step tracking"
while b:
# a, b = b, a % b
tmp = a
a = b
b = tmp % b
steps.append(a)
return steps # normally we'd want to return `a`
# but you want the steps not just the result
steps = gcd_steps(125 * 123 * 12314, 25 * 149)
# print the list with `->` between the steps
print(" -> ".join(str(x) for x in steps))
(the result would be the last step, which you can access by taking the last element of the list: steps[-1])
Output:
3725 -> 900 -> 125 -> 25
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 days ago.
Improve this question
I am new to coding in general, so after learning the basics of python from various videos on youtube, I started taking challenges on code wars. there is a particular problem I cant seem to get past. here it is :
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
we want to find a positive integer k, if it exists, such that the sum of the digits of n taken to the successive powers of p is equal to k * n.
In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n and p will always be given as strictly positive integers.
I tried using if statements but I still was not able to find the k integer, then I tried using a for loop I still had no progress. I will love it if someone gave an assistance on how to get pass this problem.
This is a problem about math and arithmetic, so it helps to think first about math and arithmetic. You can think about programming once your math is right. Math comes first. Here you are asking whether a ** p + b ** (p+1) + ... is a multiple of n. Or in other words, if it is divisible by n. See Wikipedia: Divisor or some other better math resource about arithmetic and divisibility.
a, b, c, d, ... are known. p is known. So the big number of the left of the equal sign is known. Let's call X this number. X = a ** p + b ** (p+1) + ....
n is known too.
You are asking whether X is a multiple of n. There is division and remainder for that. The answer is yes if and only if the remainder x % n is 0, and in that case, k is the quotient k = X // n.
Important note about python: powers in python are noted using **, not ^. This is important because ^ is also an operator in python, but it doesn't mean power at all. So if you write a ^ p you won't get an error with a helpful error message; instead, the code will execute but the result will be garbage. Be careful to write a ** p and not a ^ p.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
I am not able to understand the logic behind this code ,It is a code of finding a GCD
def hcf(a, b):
if(b == 0):
return a
else:
**return hcf(b, a % b)**
# a = 60
# b = 48
# prints 12
# print("The gcd of 60 and 48 is : ", end="")
print(hcf(24, 40))
As noted in the comments, function "hcf" is a function that can be called recursively. The twist to this usage for deriving the greatest common denominator lies in the fact that on each subsequent call to the function, the previous denominator used for the modulo calculation becomes the numerator and the remainder from the previous modulo calculation becomes the denominator.
def hcf(a, b):
if(b == 0):
return a
else:
print("Try", b, "and", a % b) # Every recursive call switches the numerator and denominator to be used for modula calculation
return hcf(b, a % b)
# a = 60
# b = 48
# prints 12
# print("The gcd of 60 and 48 is : ", end="")
print(hcf(24, 40))
This process zeros in on the largest value that finally attains a remainder of zero, and thus is identified as the greatest common denominator.
Inserting a print statement to view what is happening at each recursive call of this function results in the following terminal output for the values coded into your program.
#Una:~/Python_Programs/GCD$ python3 gcd.py
Try 40 and 24
Try 24 and 16
Try 16 and 8
Try 8 and 0
8
In an extreme example, if both numbers happen to be prime numbers, the greatest common denominator will be "1".
#Una:~/Python_Programs/GCD$ python3 gcd.py
Try 29 and 17
Try 17 and 12
Try 12 and 5
Try 5 and 2
Try 2 and 1
Try 1 and 0
1
It is an efficient method to attain the greatest common denominator for two natural numbers.
You might want to try out some different number combinations and review the printout to visually walk through the process.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am looking for an explanation to the solution to the front_back google python exercise. Specifically, I do not understand why the % symbol (placeholder?) is used. I also do not understand why the length of the strings are divided by 2. Especially since 2 does not equal 1 (2==1??)
The problem/solution is as follows:
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
def front_back(a, b):
# +++your code here+++
# LAB(begin solution)
# Figure out the middle position of each string.
a_middle = len(a) / 2
b_middle = len(b) / 2
if len(a) % 2 == 1: # add 1 if length is odd
a_middle = a_middle + 1
if len(b) % 2 == 1:
b_middle = b_middle + 1
return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]
# LAB(replace solution)
# return
# LAB(end solution)
THANK YOU!
It seems the statement you're most confused about is if len(a) % 2 == 1:. The % sign in this case means division with remainder (modulo). So if the length of the string were odd then dividing the length by 2 has a remainder 1 and if the length were even the remainder is 0. The if statement checks if the remainder is 1 and therefore if the length is odd.
Earlier the length strings are divided by 2 to find the middle position of the strings. However, since len(string) and 2 are both integers, python performs integer division and rounds the result down to an integer, which is why you need to add back the extra spacing unit with if statement if the length were odd.
The final statement of the code then uses the slice syntax to concatenate the string halves based on the positions found previously.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So the question reads: Design a function that accepts an integer argument and return’s the sum of all integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1,2,3,4…….50. Use recursion to calculate the sum.
im having lots of trouble as you can tell by my code
def main():
numbers= int(input('Enter a number to add the sums: ')
mysum = sum_num(numbers,1)
def sum_num(numbers,mysum):
start=1
end=numbers
if start>end:
return 0
else:
return my_sum
main()
def sumup(n):
# this one is your emergency break. you return 1 if n gets below
# a certain threshold, otherwise you'll end up with an infinite
# loop
if n <= 1:
return n
# here is the recursion step, we return (n + "the sum to n+1")
else:
return n + sumup(n-1)
print(sumup(50))
Golfing a bit:
def sumup(n):
return (n + sumup(n - 1) if n > 1 else n) if isinstance(n, int) else None
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to programming and I am trying to write a program that takes a positive integer n from input, and then outputs all factorizations of n.
For example if n=10 the program would output
1 times 10 equals 10
2 times 5 equals 10
5 times 2 equals 10
10 times 1 equals 10
I believe the easiest way to do it is to use an if statement nested within for loops. Can anybody provide me with any guidance to help create this? So far I have...
n = int(input())
a = 0
b = n
for a in range(0, n):
if a * b !=n:
continue
if a * b ==n:
print (a+ "times" +b+ "equals" +n)
a=a+1
b=n-1
But for some reason it isn't working. I think I have the right general idea but my code is obviously incorrect.
There are a few issues with your code, but also with your logic. You are increasing a twice (with for and addition), b becomes n-1 the first time through the loop and stays that way, but even if it didn't (eg b = b - 1), it wouldn't work, because if you are increasing a and decreasing b simultaneously, you won't find the correct values unless they happen to match by chance.
Other than that, it's unnecessary to check for a * b != n, you need to call str on the integers to add them to strings and the 0 in your range call is redundant.
whncode's answer is an elegant solution (except for a couple of errors I tried to correct), but to use your logic, you might do this:
for a in range(1, n+1):
for b in range(1, n+1):
if a * b == n:
print str(a) + " times " + str(b) + " equals " + str(n)
n = 10
for divisor in range(n, 0, -1): # reverse range
if (n%divisor == 0): # if modulo is 0
print("%d times %d equals %d", (n/divisor, divisor, n)