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.
Related
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 2 years ago.
Improve this question
I need to check if the given integer is a prime, and return True if so. If not, I need to find the smallest factor which is more than 1. I'm completely new to this and even though code compiles it fails several test cases.
def isPrime(n):
if (n <= 1) :
return n
if (n <= 3) :
return 1
if (n % 2 == 0 or n % 3 == 0) :
return 2
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return i
i = i + 6
return True
A prime is a number that can only be divided by one and itself. So, if we test x, we should test every number y such that 1 < y < x. A good way to test this is to use a for loop. Here is an example:
def isPrime(n):
for i in range(2,n):
if n % i == 0:
return False # because that means that something divides into n perfectly
return True
There are a few problems with this:
isPrime(1) returns True
Any negative number will return True
The program gets quite a bit slower as the numbers get bigger. For example, it takes 0.145 seconds to complete isPrime(1000003), but primes take longer to process, because as soon as a factor is found, the entire function stops and returns, whereas for a prime to be found, it has to run through every iteration up to n.
I'll leave those problems to you for the moment. In the meantime, we need a way to return the smallest factor. This is actually very easily done:
def isPrime(n):
for i in range(2,n):
if n % i == 0:
return i # i at this iteration is equal to the smallest factor
return True
So isPrime(20) returns 2, and isPrime(19) returns True. Hopefully this satisfies your needs.
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.
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 2 years ago.
Improve this question
I have the following problem:
I am given 2 natural positive numbers: d and N.
I need to find the length of the minimum d-redigit that is a multiple of N.
A natural number x is a d-redigit if x is a sequence of d's.
Example: 111111 is a 1-redigit.
There may be no d-redigit multiple of N.
I know how to solve the problem when I know that a d-redigit that is multiple of N exists. However, my question is: How can I determine if this d-redigit, multiple of N, exists?
Note: The programming language for this implementation doesn't really matter, it can be pseudo code, GCL preferably.
I have tried the following implementation in Python:
def proyect_a(n:int, d:int):
if n == 0 or d == 0:
return ''
i = 1
red = d
while i < 11 and red%n != 0:
red = 10*red + d
i+=1
if i < 11:
return len(str(red))
else:
return '*'
The previous algorithm is a brute-force partial solution, since it can't really tell the length of the minimum d-redigit for all cases. As you can see, the cycle repeats 10 times max, given that I really don't know how to check if a d-redigit multiple of N exists.
First of all, since you're only concerned about divisibility by n, there's no need to use huge integers. Just compute the value of repdigit modulo n at each step. For any value of repdigit, there are only n possible values of repdigit % n, so if you don't find a multiple of n after n iterations, you can be sure that no solution exists.
But you can do a lot better by looking for repeating cycles in the calculated values. The simplest approach would be to store each successive value of repdigit. If a value occurs twice, then that means you've entered a repeating cycle and there is no solution. But there's no need to store every value of repdigit. Each iteration of the loop is equivalent to calculating the next output of a linear congruential generator with a=10, c=d, and m=n. If you start with an initial value of zero, the output sequence will settle into a repeating cycle after at most 3 iterations.
With a bit of mathematical reasoning, you could speed up the calculations even more. What you're essentially calculating is the number of iterations that it takes for an LCG seeded with a value of zero to output zero a second time (using parameters a,c,m = 10,d,n).
For example, this LCG will produce a maximal length sequence when n and d are coprime and n is a power of 3, in which case min_repdigit_multiple(n,d) will be equal to n. There are probably other short cuts you could take.
def min_repdigit_multiple(n:int, d:int):
#
# Returns the length of the smallest repdigit number divisible by n
# i.e. the smallest value of x such that ((10**x-1)*d//9) % n == 0
# If no solution exists, returns -1 instead
#
assert 0 < d <= 9, "d must be a single non-zero digit"
#
# Check for a maximal length LCG sequence
from math import gcd
if gcd(n,d) == 1:
n0 = n
while n0 % 3 == 0:
n0 //= 3
if n0 == 1:
return n
#
i = 1
repdigit = 0
seen = set()
while i <= n:
repdigit = (10 * repdigit + d) % n
if repdigit in seen:
# We've been here before, so there is no solution
return -1
if repdigit == 0:
# Success: repdigit is divisible by n
return i
# There's no point in storing more
# than the first few values of repdigit
if i < 4:
seen.add(repdigit)
i += 1
return -1 # Searched all possible values without finding a solution
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)
This question already has answers here:
How to create the most compact mapping n → isprime(n) up to a limit N?
(29 answers)
Closed 7 years ago.
I'm trying to do a simple primality test in Python.
Accoding to Wikipedia, a primality test is the following:
Given an input number n, check whether any integer m from 2 to n − 1 divides n. If n is divisible by any m then n is composite, otherwise it is prime.
I started with ruling out the even numbers - with the exception of 2 - as candidates to prime
def prime_candidates(x):
odd = range(1, x, 2)
odd.insert(0, 2)
odd.remove(1)
return odd
Then writing a function to check for primes, according to the rules above.
def isprime(x):
for i in range(2, x-1):
if x % i == 0:
return False
else:
return True
And this is the main function, which iterates over a list of 8000 prime candidates and tests their primality
def main():
end = 8000
candidates = prime_candidates(end)
for i in candidates:
if isprime(i) and i < end:
print 'prime found ' + str(i)
The problem is that the isprime function returns True for numbers that aren't primes.
Have a look at the Miller–Rabin primality test if a probabilistic algorithm will suffice. You could also prove a number to be prime, with for instance Elliptic Curve Primality Proving (ECPP), but it takes more effort.
A simple trial division algorithm is the following
def prime(a):
return not (a < 2 or any(a % x == 0 for x in range(2, int(a ** 0.5) + 1)))
Edit:
Here's a more educational version because the first solution is very condensed and perhaps harder to read:
from math import sqrt
def prime(a):
if a < 2: return False
for x in range(2, int(sqrt(a)) + 1):
if a % x == 0:
return False
return True
I've substituted in sqrt(a) in place of a ** 0.5 to make things more clear. The square root is used to not look at more factors than we have to.
In brief, your isprime(x) checks whether the number is odd, exiting right after if x % 2 == 0.
Try a small change so that you would actually iterate:
def isprime(x):
for i in range(2, x-1):
if x % i == 0:
return False
else:
return True
Note that else: is now part of the for loop rather than if statement.
Your function actually returns whether your number is odd.
Indeed, what you're doing is you're checking whether 2 divides your number, and return immediately. You never check for the other numbers.
What you need to do is take this return true out of the if's else clause and the for loop back into the main function body.
On a sidenote, If you're looking for the primes lower than a given number, you could store the primes you found in memory and then only try dividing you new number by those primes !
(because if d is composite and divides q, then p exists such that p is prime and p divides q).
The problem is that you put return False in the else clause rather than at the end of the function. So your function will return right after the first divisor is checked, rather than going on to check other divisors.
Here is a simple primality test similar to yours:
def is_prime(n):
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return n > 1