Primes in arithmetic progressions in Sagemath - primes

I am in need of finding prime numbers in arithmetic progression
80218110*n+8021749, n=1 to 100,000
I was told that using Sage would be a good option, since my computer is old. I happen to be new to Sage and I haven't found it to solve my problem, I guess it shouldn't be difficult, does anyone have a good reference for printing primes in arithmetic progressions?

SageMath is based on Python, and Python provides a syntax which should be comfortable for mathematicians:
[80218110*n + 8021749 for n in range(100)]
range(100) is the ordered set 0, 1, 2, ..., 99, and so the previous line evaluates 80218110*n + 8021749 for these values of n. We can also test whether the entries are prime:
INPUT: [80218110*n+8021749 for n in range(100) if (80218110*n+8021749).is_prime()]
OUTPUT:
[8021749,
489330409,
569548519,
970639069,
1050857179,
1131075289,
1772820169,
2093692609,
2173910719,
3136528039,
3617836699,
4660672129,
4740890239,
5382635119,
6425470549,
7067215429,
7227651649,
7548524089]
You can of course make the argument to range larger, but maybe it's not a good idea to print the whole list.
INPUT: len([80218110*n+8021749 for n in range(100000) if (80218110*n+8021749).is_prime()])
OUTPUT: 15273
(len returns the length of the list.) Producing this list is pretty quick, at least on my computer:
INPUT: %time L = [80218110*n+8021749 for n in range(100000) if (80218110*n+8021749).is_prime()]
OUTPUT CPU times: user 94.6 ms, sys: 1.13 ms, total: 95.8 ms
Wall time: 95.5 ms
(ms is milliseconds.)

Related

Executing a file a large number of times

How do I get a file to run a large number of times, say even a million? For instance, randomly choose a number from a list a million times and find it's average. Example:
fib = [2,3,5,8,13,21,34,55,89]
i = random.choice(fib)
print i
I want the average of a million trials. It seems like the method around here is to help and not so much feed me the answer. That is greatly appreciated as well.
How about looping a million times, summing up the chosen values and dividing by a million:
from __future__ import print_function
import random
n = 1e6
fib = [2,3,5,8,13,21,34,55,89]
print(sum(random.choice(fib) for _ in range(int(n))) / n)
Output:
25.565039
The above code contains a generator expression. It is equivalent to this loop version:
sum_ = 0
for x in range(int(n)):
sum_ += random.choice(fib)
print(sum_/n)
Output:
25.576006

division gives 0 in loop, why?

the code below gives me 0% for each 20th iteration, instead of the actual percentage I would like it to show.
n=100
for i in range(n):
if i% 20 ==0:
print str(i/n*100) + '%, Progress'
Results:
0%, Progress
0%, Progress
etc.....
I must be missing something really simple. Thank you.
change the division to i/(float)n*100 so that the resulting output will be formatted to decimal points by the python interpreter.
Division automatically rounds down to the nearest integer.
What happens in your code is:
i = 20
n = 100
i/n = 20/100, which becomes 0.
Then (i/n)*100 = 0*100 = 0.
You could solve this by first multiplying i by 100 and then dividing by n:
i*100/n
n=100
for i in range(n):
print(i);
if i% 20 ==0:
print str((float(i)/float(n))*100) + '%, Progress'
for python i/n is an (int)/(int) according to your variable declaration. so ti tries to give an int answer for i/n which is always 0.
In each iteration i/n*100 gets rounded down to the nearest integer (this is how the division operator works on integers in python2).
You could either use explicit casting to float() or execute from __future__ import division beforehand. This would prevent the division operator from rounding down automatically.
Here you can find a detailed description of a similar problem.

Python number averages using lists and keys

I'm working on a Python assignment and I'm totally stuck. Any assistance would be greatly appreciated. I know it's probably not as convoluted as it seems in my head... The details are below. Thanks very much.
Implement the following three functions (you should use an appropriate looping construct to compute the averages):
allNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list.
posNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are greater than zero.
nonPosAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are less than or equal to zero.
Write a program that asks the user to enter some numbers (positives, negatives and zeros). Your program should NOT ask the user to enter a fixed number of numbers. Also it should NOT ask for the number of numbers the user wants to enter. But rather it should ask the user to enter a few numbers and end with -9999 (a sentinel value). The user can enter the numbers in any order. Your program should NOT ask the user to enter the positive and the negative numbers separately.
Your program then should create a list with the numbers entered (make sure NOT to include the sentinel value (-9999) in this list) and output the list and a dictionary with the following Key-Value pairs (using the input list and the above functions):
Key = 'AvgPositive' : Value = the average of all the positive numbers
Key = 'AvgNonPos' : Value = the average of all the non-positive numbers
Key = 'AvgAllNum' : Value = the average of all the numbers
Sample run:
Enter a number (-9999 to end): 4
Enter a number (-9999 to end): -3
Enter a number (-9999 to end): -15
Enter a number (-9999 to end): 0
Enter a number (-9999 to end): 10
Enter a number (-9999 to end): 22
Enter a number (-9999 to end): -9999
The list of all numbers entered is:
[4, -3, -15, 0, 10, 22]
The dictionary with averages is:
{'AvgPositive': 12.0, 'AvgNonPos': -6.0, 'AvgAllNum': 3.0}
EDIT: This is what I have so far, which I did pretty quick just to have a something to work with but I can't figure out how to implement the keys/dictionary like the assignment asks. Thanks again for any help.
print("This program takes user-given numbers and calculates the average")
counter = 0
sum_of_numbers = 0
first_question = int(input('Please enter a number. (Enter -9999 to end):'))
while first_question != -9999 :
ent_num = int(input('Please enter a number. (Enter -9999 to end):'))
sum_of_numbers = sum_of_numbers + ent_num
counter = counter + 1
first_question = int(input('Please enter a number (Enter -9999 to end):'))
print("Your average is " + str(sum_of_numbers/counter))
Welcome to Python programming, and programming in general!
From your code, I assume you are not entirely familiar with Python lists, dictionaries, and functions and how to use them. I'd suggest you look up tutorials for these; knowing how to use them will make your assignment much easier.
Here are some tutorials I found with some quick searches that might help:
Dictionary Tutorial,
List Tutorial,
Function Tutorial
When your assignment says to make three functions, you should probably make actual functions rather than trying to fit the functionality into your loop. For example, here is a simple function that takes in a number and adds 5 to it, then returns it:
def addFive(number):
return number + 5
To use it in your code, you would have something like this:
num = 6 # num is now 6
num = addFive(num) # num is now 11
So what you should do is create a list object containing all the numbers the user entered, and then pass that object into three separate functions - posNumAvg, nonPosAvg, allNumAvg.
Creating a dictionary of key-value pairs is pretty easy - first create the dictionary, then fill it with the appropriate values. For example, here is how I would create a dictionary like {'Hello': 'World'}
values = {}
values['Hello'] = 'World'
print(values) # Will print out {'Hello': 'World'}
So all you need to do is for each of the three values you need, assign the result of the function call to the appropriate key.
If this doesn't feel like quite enough for you to figure out this assignment, read the tutorials again and play with lists, dictionarys, and functions to try and get a feel for them. Good luck!
P.S. The append method of lists will be helpful to you. Try to figure out how to use it!

Count the number of possible permutations of numbers less than integer N, given N-1 constraints

We are given an integer N and we need to count the total number of permutations of numbers less than N. We are also given N-1 constraints. e.g.:
if N=4 then count permutations of 0,1,2,3 given:
0>1
0>2
0>3
I thought about making a graph and then counting total no of permutation of numbers at same level and multiply it with permutations at other level.e.g.:
For above example:
0
/ | \
/ | \
1 2 3 ------> 3!=6 So total no of permutations are 6.
But I have difficulty in implementing it in C++. Also, this question was asked in Facebook hacker cup, the competition is over now. I have seen code of other people and found that they did it using DFS. Any help?
The simplest way to do this is to use a standard permutation generator and filter out each permutation that violates the conditions. This is obviously very inefficient and for larger values of N is not computable. Doing this is sort of the "booby" option that these contests have which allows the less smart contestants to complete the problem.
The skilled approach requires insight into the ways of counting combinations and permutations. To illustrate the method I will use an example. Inputs:
N = 7
2 < 4
0 < 3
3 < 6
We first simplify this by combining the dependent conditions into a single condition, as follows:
2 < 4
0 < 3 < 6
Start with the longest condition, and determine the combination count of the gaps (this is the key insight). For example, some of the combinations are as follows:
XXXX036
XXX0X36
XXX03X6
XXX036X
XX0XX36
etc.
Now, you can see there are 4 gaps: ? 0 ? 3 ? 6 ?. We need to count the possible partitions of X's in these four gaps. The number of such partitions is (7 choose 3) = 35 (do you see why?). Now, we next multiply by the combinations of the next condition, which is 2 < 4 over the remaining blank spots (the Xs). We can multiply because this condition is fully independent of the 0<3<6 condition. This combination count is (4 choose 2) = 6. The final condition has 2 values in 2 spots = 2! = 2. Thus, the answer is 35 x 6 x 2 = 420.
Now, let's make it a little more complicated. Add the condition:
1 < 6
The way this changes the calculation is that before 036 had to appear in that order. But, now, we have three possible arrangements:
1036
0136
0316
Thus, the total count is now (7 choose 4) x 3 x (3 choose 2) = 35 x 3 x 3 = 315.
So, to recap, the procedure is you isolate the problem into independent conditions. For each independent condition you calculate the combinations of partitions, then you multiply them together.
I have walked through this example manually, but you can program the same procedure.

Time based rotation

I'm trying to figure out the best way of doing the following:
I have a list of values: L
I'd like to pick a subset of this list, of size N, and get a different subset (if the list has enough members) every X minutes.
I'd like the values to be picked sequentially, or randomly, as long as all the values get used.
For example, I have a list: [google.com, yahoo.com, gmail.com]
I'd like to pick X (2 for this example) values and rotate those values every Y(60 for now) minutes:
minute 0-59: [google.com, yahoo.com]
minute 60-119: [gmail.com, google.com
minute 120-179: [google.com, yahoo.com]
etc.
Random picking is also fine, i.e:
minute 0-59: [google.com, gmail.com]
minute 60-119: [yahoo.com, google.com]
Note: The time epoch should be 0 when the user sets the rotation up, i.e, the 0 point can be at any point in time.
Finally: I'd prefer not to store a set of "used" values or anything like that, if possible. i.e, I'd like this to be as simple as possible.
Random picking is actually preferred to sequential, but either is fine.
What's the best way to go about this? Python/Pseudo-code or C/C++ is fine.
Thank you!
You can use the itertools standard module to help:
import itertools
import random
import time
a = ["google.com", "yahoo.com", "gmail.com"]
combs = list(itertools.combinations(a, 2))
random.shuffle(combs)
for c in combs:
print(c)
time.sleep(3600)
EDIT: Based on your clarification in the comments, the following suggestion might help.
What you're looking for is a maximal-length sequence of integers within the range [0, N). You can generate this in Python using something like:
def modseq(n, p):
r = 0
for i in range(n):
r = (r + p) % n
yield r
Given an integer n and a prime number p (which is not a factor of n, making p greater than n guarantees this), you will get a sequence of all the integers from 0 to n-1:
>>> list(modseq(10, 13))
[3, 6, 9, 2, 5, 8, 1, 4, 7, 0]
From there, you can filter this list to include only the integers that contain the desired number of 1 bits set (see Best algorithm to count the number of set bits in a 32-bit integer? for suggestions). Then choose the elements from your set based on which bits are set to 1. In your case, you would use pass n as 2N if N is the number of elements in your set.
This sequence is deterministic given a time T (from which you can find the position in the sequence), a number N of elements, and a prime P.