Python factorization program [closed] - python

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)

Related

How can I repeatedly divide a number by the elements of a list? [closed]

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 2 years ago.
Improve this question
divisors = []
def check_for_prime(x):
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
if isinstance(divisors, float):
yield x
When I try to run this code, it shows an error: 'list object cannot be interpreted as an integer'. How can I fix this so the loop can successfully divide everything?
It seems like you are trying to check if a given number is prime through list comprehension. There are a good bunch of things wrong with your logic-
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
I believe you're trying to find a list of divisors for x here. This makes no sense though, even if I assume that you thought x != any([0, 1, x]) means "if x is either 0, 1, or x" (that's not actually what this code means). Wouldn't that statement always be true? I mean x has got to be x (unless it's nan, but that's a different topic).
If you wanted to express "if x is either 0, 1 or x" in python, you'd use if x in [0, 1, x] (you shouldn't want to though since that makes 0 sense as explained above). Not any. Read what any does.
To get a list of divisors for x, you should instead do-
divisors = [d for d in range(2, math.floor(x/2) + 1) if x % d == 0]
Essentially, you start from 2 (not 0 because that's impossible, and not 1 because we want to avoid that for prime checking), and stop at half the given number (because after that point, you can't divide the given number and get an integral result). Throughout this range, you only add those d for which x % d is 0. I.E, the result is integral. Notice, 6 % 3 is 0, because 3 is indeed a divisor of 6.
I have 0 clue what the hell you're trying to do here though-
if isinstance(divisors, float):
yield x
You're checking whether or not divisors is a float? why? you already know it's a list, you made it in the previous line.
I think you want to know if the given number is a prime or not. In that case, you can just check if the length of divisors is more than 0.
return len(divisors) > 0
Edit: As #RiccardoBucco mentioned below. If you don't want the list of divisors at all, you can simply return as soon as you find a divisor. A simple loop will suffice for that.
for d in range(2, math.floor(x/2) + 1):
if x % d == 0:
# x is not prime
return False
# x is prime
return True
However, DO NOT forget to factor in the exceptional case when x = 1, 1 is not a prime number. Should be factored in both the for loop and the list comprehension method.
You are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in list.
This will always fail because you're creating a new list by using the comprehension in line 3. Line 4 will always evaluate to False because a list is obviously not a float.

Why does % work and / does not in filtering out even numbers? [closed]

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 2 years ago.
Improve this question
Compare these two blocks, there's only an operator difference;
for i in range(0, 10):
if i / 2 == 0:
continue
print(i)
and
for i in range(0, 10):
if i % 2 == 0:
continue
print(i)
Why does the second block of code work in successfully filtering out even numbers while the first block does not? I can't wrap the logic around my head. Intuitively any even number should be divisible by 2, so why does the first block not work and prints every number in the range?
Becasuse % takes the reminder of the division (ref, ref), and / gives you the result of the divison (ref).
i / 2 == 0 is only True if i=0.
i % 2 == 0 is only True if i is divisible by 2 (ie you can divide it without getting a remainder, ie it is even).
Because modulo (%) checks divisibility, while division (/) doesn't. This is more of a math question than programming.
If a number N is divisible by another number M, N mod M will be 0. Meanwhile, N divided by M will be K, where K times M equals N, and K will be a whole number since N is divisible by M.
So if you wanted to check divisibility using division, you could check if K is a whole number:
for i in range(0, 10):
k = i / 2
if k == int(k):
continue
print(i)
But don't do this. Modulo is much simpler.
References
Tutorial: Numbers
Binary arithmetic operations
If you want to use division as operation then that's the solution.
for i in range(0, 10):
if (i // 2) * 2 != i:
continue
print(i)
The difference is that by using % you will be getting the modulo % 2 gives you 1 or 0 depending if the number is even or odd. /2 will give you the number divided by 2.

Python script- need help understanding this while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My gf is studying CS and needs help understanding how this script runs and why?
What value does mystery(9870) return?
def mystery(n):
m = " "
while n > 0:
m += str(n % 10)
n //= 10
return m
The possible answers are-
"789"
"0789"
"7890"
"987"
"9870"
We just need to know how the code runs?
Can anyone help?
This is the proper indentation you need to use.
def mystery(n):
m = ""
while n > 0:
m += str(n % 10)
n //= 10
return m
When you call the function:
mystery(9870)
' 0789'
The function takes a parameter and checks if it is greater than 0. While the condition is satisfied, it divides the number by 10 and converts the remainder into a string and appends it to an empty string m. n //= 10 will remove the last digit of the number and stores the remaining in n. And the while loop checks if n is greater than 0 again. Etc.. The whole thing continues until n is a single digit number at which point, n//=10 will return 0 and the condition of while loop will not satisfy.
Basically, it reverses the digits of the number you pass as parameter.
Hope this explanation helps.

What is going on in this code (Python 2.7)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
I received an assignment where I had to find the sum of all prime numbers up to 2 million and the code I wrote originally took way too long to run so the teacher gave me this algorithm to check if the number is prime. However, I don't quite seem to get what's going on in the return all statement and what it has to do with prime numbers
Since I was not nice to you. Let me just make a little extra effort and explain it you.
First read this:
http://wiki.planetmath.org/howtofindwhetheragivennumberisprimeornot
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
Let's see whats happening here.
Step1. if n % 2 == 0 and n > 2
Check if the number is divisible by 2 and also greater than 2. If these condition fail then the number is not prime. Don't proceed any further and return false.
Step2a. int(math.sqrt(n)) + 1
Calculate the square root of the number (it might be float so we convert it into int) and then add 1 to it.
Step2b. range(3, int(math.sqrt(n)) + 1, 2)
Create a list starting from 3 to the value calculated in step2a with a step size of 2. So basically it will get all the odd numbers from 3 to step2a value. Why just odd? Because evens are not prime!
Step2c. (n % i for i in range(3, int(math.sqrt(n)) + 1, 2)
In this step we are iterating over the list created in 2b and dividing n by all of those numbers (by dividing here i mean taking modulus) and we are storing the results in an iterator object.
Step2d. all()
If n was divisible by any number of list from 2b, then a 0 will be stored on n % i. And we know that a prime number is not divisible by any number other than 1 and itself. If we get a 0 then we are done, it's not a prime number.
all() will return true only if all the values are non zero.
Eg.
print all([1,2,3,4,5])-->True
print all([0,1,2,3,4])-->False
I hope, now it's clear to you.

Greatest Common Denominator counter [closed]

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

Categories