def i4_to_van_der_corput_test ( ): #*****************************************************************************80 # ## I4_TO_VAN_DER_CORPUT_TEST tests I4_TO_VAN_DER_CORPUT. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 12 May 2015 # # Author: # # John Burkardt # import numpy as np from prime import prime n_prime = 5 n_test = 10 print '' print 'I4_TO_VAN_DER_CORPUT_TEST' print ' I4_TO_VAN_DER_CORPUT computes the elements' print ' of a van der Corput sequence.' print ' The sequence depends on the prime numbers used' print ' as a base.' print '' print ' Bases:' print '' print '' for j in range ( 1, n_prime + 1 ): print ' %6d' % prime ( j ), print '' print '' h = np.zeros ( n_prime ) for i in range ( 0, n_test ): for j in range ( 1, n_prime + 1 ): jm1 = j - 1 p = prime ( j ) h[jm1] = i4_to_van_der_corput ( i, p ) print ' %2d' % ( i ), for j in range ( 1, n_prime + 1 ): jm1 = j - 1 print ' %12f' % ( h[jm1] ), print '' # # Terminate. # print '' print 'I4_TO_VAN_DER_CORPUT_TEST' print ' Normal end of execution.' return
def answer(limit=11): hits, total = 0, 0 for pos in count(): if is_truncatable_prime(prime(pos)): hits += 1 total += prime(pos) if hits == limit: return total
def rec(currents, ps): if len(currents) == 5: print(currents, sum(i for i in currents)) sys.exit(0) for p in ps: if p <= currents[-1]: continue for c in currents: if not prime(int(str(c) + str(p))) or \ not prime(int(str(p) + str(c))): break else: rec(currents + [p], ps)
def e26(): m = 0 for x in prime(1000): s = len(divide(1, x)) if s > m: m = s print x, m
def sum_prime_square(i, j): """ I = ith prime number returns I + 2*(j**2) """ i = pr.prime(i) return i + 2*(j**2)
def write_primes(): primes = [] for i in range(2001, int(sqrt(10000000)) + 1000, 2): if prime(i): primes.append(i) primes_file = open('70.txt', 'wb') pickle.dump(primes, primes_file)
def calc(self): while True: p = prime(self.range).get_prime() q = prime(self.range).get_prime() if p != q: break n = p * q t = (p - 1) * (q - 1) for e in range(2, t): if gcd(e, t) == 1: break for i in range(1, 10): x = 1 + i * t if x % e == 0: d = x // e if d != e: break return n, e, d, p, q, t
if not factor in primes_set: factors += prime_factors(factor, primes_set) else: factors.append(factor) n /= factor if n != 1: factors.append(n) return set(factors) primes = [] for i in range(2, 1000000): if prime(i): primes.append(i) primes_set = set(primes) totient_values_tally = 0 for number in range(2, 1000001): if number in primes_set: totient_values_tally += number - 1 else: j = number prime_factors_list_denominator = prime_factors(number, primes_set) for i in prime_factors_list_denominator: j = j * (i - 1) / i totient_values_tally += j print totient_values_tally
# (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. r = xrange(1, 101) a = sum(r) print a * a - sum(i * i for i in r) # 4.) # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? import prime print prime.prime(10000) # 5.) # Fizz Buzz for num in range(1, 100): if num % 5 == 0 and num % 3 == 0: print "FizzBuzz" elif num % 3 == 0: print "Fizz" elif num % 5 == 0: print "Buzz" else: print num
import prime MAX = 5000 prime.prime(MAX) def check_length(n, below): maxprime = 0 for x in xrange(0, below): total = sum(prime.prime_list[x : x + n]) if total > below: break if prime.isprime(total): maxprime = total return maxprime for n in xrange(1000, 0, -1): maxprime = check_length(n, 1000000) if maxprime: print maxprime break
import prime def get_index_of_closest_lower(digits, target): closest_value = -10 closest_index = 0 for i in xrange(0, len(digits)): difference = int(target) - int(digits[i]) if difference > 0 and difference < int(target) - int(closest_value): closest_value = digits[i] closest_index = i return closest_index prime_finder = prime.prime('bil') def next_highest_permutation(digits): for i in xrange(len(digits) - 1, 0, -1): if digits[i] < digits[i - 1]: lower = digits[i] higher = digits[i - 1] remainder = digits[i:] index_of_closest_lower = get_index_of_closest_lower( remainder, higher) remainder = remainder[:index_of_closest_lower] + remainder[ index_of_closest_lower + 1:] remainder = higher + remainder digits = digits[0:i - 1] + digits[i + index_of_closest_lower] + ''.join( sorted(remainder, reverse=True))
from time import time from prime import prime start = time() i = 10 p = [] while len(p) < 11: if prime(i) and all(prime(int(str(i)[:j])) and prime(int(str(i)[j:])) for j, _ in enumerate(str(i)) if j > 0): p.append(i) i += 1 print('Evaluated {} numbers in {} seconds'.format(i, time() - start)) print('Found these: {}'.format(p)) print('Sum: {}'.format(sum(i for i in p)))
y = input("Enter the filename of the second database :") with open("../../../../data/" + x) as dict: dict1 = dict.read().split('\n') with open("../../../../data/" + y) as dict: dict2 = dict.read().split('\n') if len(dict1) < len(dict2): n = len(dict2) else: n = len(dict1) p = 0.18 m1 = ((float(n) * float(math.log(p))) / float(math.log(1.0 / (math.pow(2, float(math.log(2))))))) k = (float(math.log(2)) * float(m1) / float(n)) #print (math.floor(m),math.floor(k)) LENNY = prime.prime(math.ceil(m1)) m = [None for i in range(LENNY)] if len(dict1) > len(dict2): for i in range(len(dict1)): a = [] a = dict1[i] n = mmh3.murmur(a.lower()) n = n % LENNY f = fnv.fnv(a.lower()) f = f % LENNY q = horner.hash3(a.lower()) q = q % LENNY m[n] = 1 m[f] = 1 m[q] = 1
#!/usr/bin/env python2 from math import sqrt from prime import prime_int as prime number = 600851475143 start = int(sqrt(number)) if not start % 2: start += 1 for n in xrange(start, 0, -2): if not prime(n): continue if not number % n: break print "result: %s" % n
#!/usr/bin/python3 from prime import prime number = 1 counter = 1 while counter != 10001: if prime(number): counter += 1 number += 2 print(number - 2)
from prime import prime from itertools import takewhile from time import time from math import sqrt # doing it the other way around might save loads of time # this is way too slow # this is as slow as a frozen zenyatta # this shit is so slow your fat mom could run faster primes = [i for i in xrange(2, 1000000) if prime(i)] start = time() ma, mp = 509, 0 for q in primes[-300:]: alternatestart = time() print(q) i = 0 while i < int(sqrt(len(primes))): s = 0 c = 0 for j in takewhile(lambda x: s < q, primes[i:]): s += j c += 1 if s == q: if c > ma: ma = c mp = q break i += 1 print(mp, ma, time() - alternatestart) print(mp, ma, time() - start)
def i4_factor(n): #*****************************************************************************80 # ## I4_FACTOR factors an integer into prime factors. # # Formula: # # N = NLEFT * Product ( 1 <= I <= NFACTOR ) FACTOR(I)^POWER(I). # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 14 February 2015 # # Author: # # John Burkardt # # Parameters: # # Input, integer N, the integer to be factored. N may be positive, # negative, or 0. # # Output, integer NFACTOR, the number of prime factors of N discovered # by the routine. # # Output, integer FACTOR(NFACTOR), the prime factors of N. # # Output, integer POWER(NFACTOR). POWER(I) is the power of # the FACTOR(I) in the representation of N. # # Output, integer NLEFT, the factor of N that the routine could not # divide out. If NLEFT is 1, then N has been completely factored. # Otherwise, NLEFT represents factors of N involving large primes. # from prime import prime nfactor = 0 factor = [] power = [] nleft = n if (n == 0): return nfactor, factor, power, nleft if (abs(n) == 1): nfactor = 1 factor.append(1) power.append(1) return nfactor, factor, power, nleft # # Find out how many primes we stored. # maxprime = prime(-1) # # Try dividing the remainder by each prime. # for i in range(1, maxprime + 1): p = prime(i) if (((abs(nleft)) % p) == 0): nfactor = nfactor + 1 factor.append(p) power.append(0) while (True): power[nfactor - 1] = power[nfactor - 1] + 1 nleft = (nleft // p) if (((abs(nleft)) % p) != 0): break if (abs(nleft) == 1): break return nfactor, factor, power, nleft
from prime import prime from math import sqrt from time import time t = time() square_max = 7072 cube_max = 369 quart_max = 85 primes = [i for i in range(2, square_max + 1) if prime(i)] squares = [i for i in primes if i <= square_max] cubes = [i for i in primes if i <= cube_max] quarts = [i for i in primes if i <= quart_max] numbers = [] for square in squares: sum = square ** 2 for cube in cubes: sum += cube ** 3 if sum >= 50000000: sum -= cube ** 3 break for quart in quarts: sum += quart ** 4 if sum < 50000000:
def test_1の時(self): p=prime.prime(1) self.assertEqual(p,False)
def test_素数じゃない時(self): p=prime.prime(4) self.assertEqual(p,False)
def test_素数の時(self): p=prime.prime(3) self.assertEqual(p,True)
def test_0以下の時(self): p=prime.prime(-1) self.assertEqual(p,False)
from prime import prime from time import time start = time() ma, mb, mn = 0, 0, 0 for a in xrange(-999, 1000): for b in xrange(-999, 1000): n = 0 try: while prime(n * n + a * n + b): n += 1 if n > mn: ma, mb, mn = a, b, n except ValueError: continue print(ma * mb) print(time() - start)
def test_for_zero(self): """Test that zero returns an empty list""" self.assertEqual(prime(0), [], msg="Zero should return an empty list")
import prime print(prime.prime(10001))
import prime print(prime.prime(10000))
def send(): # If something is sent via the submit button if request.method == 'POST': # Turn the inputted option in the drop down to a string and save it as a variable name = request.form.get('name') name = str(name) # Store the current timestamp as a variable for later plot naming now = time.strftime("%Y%m%d-%H%M%S") # Check to make sure the name is in the dataframes in the backend isin = Animation.isin(name) # Get last name by splitting the full name and pull out the second element # Turn it lower case to match the file name lastname = name.split()[1].lower() # Get the usage file name for everybody usagefile = name + '_usage_light.png' # Conditionals to fill in based on the user input strikes = int(request.form.get('strikes')) balls = int(request.form.get('balls')) outs = int(request.form.get('outs')) bat = str(request.form.get('bat')) inning = int(request.form.get('inning')) prev = str(request.form.get('pitch')) game = str(request.form.get('game')) r1 = str(request.form.get('r1')) r2 = str(request.form.get('r2')) r3 = str(request.form.get('r3')) # Input fields must be retrieved a bit differently than drop down/checkboxes pit_score = int(request.form['pscore']) bat_score = int(request.form['bscore']) # Read in the template df = pd.read_csv('for_inputs.csv', index_col=0) # Fill it out based on form values # Scores are filled out as is, no need for if statements df['bat_score'] = bat_score df['fld_score'] = pit_score # If statements for strikes if strikes == 0: df['s__0'] = 1 elif strikes == 1: df['s__1'] = 1 else: df['s__2'] = 1 # If statements for balls if balls == 0: df['b__0'] = 1 elif balls == 1: df['b__1'] = 1 elif balls == 2: df['b__2'] = 1 else: df['b__3'] = 1 # If statements for outs if outs == 0: df['o__0'] = 1 elif outs == 1: df['o__1'] = 1 else: df['o__2'] = 1 # If statements for innings if inning < 4: df['early'] = 1 elif inning > 3 and inning < 7: df['mid'] = 1 elif inning > 6: df['late'] = 1 # If statements for batter handedness if bat == 'right': df['bat_right'] = 1 elif bat == 'left': df['bat_left'] = 1 # If statements for game type if game == 'reg': df['reg_season'] = 1 elif game == "post": df['post_season'] = 1 # If statements for previous pitch # Conditional only for Zack Greinke since he's the only one with 'junk' pitches # Its 'proper' place is before the 'prev__None' columns if name == 'Zack Greinke': # argwhere creates an array of arrays, fish out the number through indexing to get rid of layers # Need to make sure to turn to int instead of np.int for the pd.insert function loc = int(np.argwhere(df.columns == 'prev__None')[0][0]) df.insert(loc, 'prev__Junk', 0) if prev == 'fb': df['prev__Fastball'] = 1 elif prev == 'bb': df['prev__Breaking Ball'] = 1 elif prev == 'os': df['prev__Off-speed'] = 1 elif prev == "jk": df['prev__Junk'] = 1 # If statements for runners # Want to consider all options so make 3 different if clauses rather than elif clauses (terminate if clause once one equals True) # Default is all zeroes (ie. no runners on), so no need to include that into the clause if r1 == 'first': df['on_1b'] = 1 if r2 == 'second': df['on_2b'] = 1 if r3 == 'third': df['on_3b'] = 1 # If the player name does exist if isin == True: pitchfile = name + '_pitches.png' # Run the model with the name of player, user-input dataframe and current timestamp pred = rm.run_model(name, df, now) # Run the scenario sentence generator with the user-input dataframe scenario = rm.scenario(df) proba_plot = 'prob_' + now + '.png' # Call the custome prime.py script to calculate a player's prime years prime_years = prime.prime(name) # Run the create dynamic radar plot function Animation.dynamic(name, now) # Create the name of the animated plot to be made filename = 'script' + now + '.gif' # Run the static radar plot of average career attributes Animation.static(name, now) # Plot file name staticradar = 'static' + now + '.png' # Run the create plot of career attributes over age function Animation.progression(name, now) prog_name = 'prog' + now + '.png' return render_template('send.html', playername=name, file=filename, pitchfile=pitchfile, usagefile=usagefile, proba_plot=proba_plot, pred=pred, situation=scenario, years=prime_years, progfile=prog_name, staticradar=staticradar) # If the player name does not exist in the database then send them to an error page else: return render_template('error.html')
import prime print prime.prime(11) print prime._isprime(32) print prime.isprime(11)
def answer(num): """ returns the num-th prime """ return prime(num - 1)
Make sure it is large. Otherwise, it will not be as consecutively random. """ # User input information print "." * 100 print "How many random numbers do you want?" n = int(raw_input('> ')) print "." * 100 print "Do you want the random numbers fixed in the range of the amount of random numbers that you wanted? (y/n)" random_number_ranged = raw_input('> ') print "." * 100 # Instance of prime object thatnumber = prime() # Initialization of variables and constants a = randint(0, n ** 2) b = randint(0, n ** 2) initial1 = randint(0, n) SEED = randint(0, 1000) random.seed(SEED) N = n i = 0 x = [] y = [] # Assign important functions nessisary for the operation. def sign_convention(): return choice([True, False])
#!/usr/bin/python import prime, string prime._refresh(80000) def is_8_prime_family(p, d): c = 0 for r in '0123456789': np = int(string.replace(p, d, r)) if(np > 100000 and np < 999999 and prime.isprime(np)): c += 1 return c==8 n=9000 while(True): n += 1 p = prime.prime(n) if p < 100000: continue if p > 999999: break ps = str(p) ld = ps[5:6] if (ps.count('0')==3 and is_8_prime_family(ps, '0')) or (ps.count('1')==3 and ld!='1' and is_8_prime_family(ps, '1')) or \ (ps.count('2')==3 and is_8_prime_family(ps, '2')): print "Answer: %s %s" % (n, ps) break
import prime as p f1 = open('output.txt', 'w') f2 = open('input.txt', 'r') n1 = f2.readline() n2 = f2.readline() f1.write("The prime numbers within the range are: \n") for i in range(int(n1), int(n2)): if p.prime(i): f1.write(str(i)) f1.write("\n") f1.close()
def i4_factor ( n ): #*****************************************************************************80 # ## I4_FACTOR factors an integer into prime factors. # # Formula: # # N = NLEFT * Product ( 1 <= I <= NFACTOR ) FACTOR(I)^POWER(I). # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 14 February 2015 # # Author: # # John Burkardt # # Parameters: # # Input, integer N, the integer to be factored. N may be positive, # negative, or 0. # # Output, integer NFACTOR, the number of prime factors of N discovered # by the routine. # # Output, integer FACTOR(NFACTOR), the prime factors of N. # # Output, integer POWER(NFACTOR). POWER(I) is the power of # the FACTOR(I) in the representation of N. # # Output, integer NLEFT, the factor of N that the routine could not # divide out. If NLEFT is 1, then N has been completely factored. # Otherwise, NLEFT represents factors of N involving large primes. # from prime import prime nfactor = 0 factor = [] power = [] nleft = n if ( n == 0 ): return nfactor, factor, power, nleft if ( abs ( n ) == 1 ): nfactor = 1 factor.append ( 1 ) power.append ( 1 ) return nfactor, factor, power, nleft # # Find out how many primes we stored. # maxprime = prime ( -1 ) # # Try dividing the remainder by each prime. # for i in range ( 1, maxprime + 1 ): p = prime ( i ) if ( ( ( abs ( nleft ) ) % p ) == 0 ): nfactor = nfactor + 1 factor.append ( p ) power.append ( 0 ) while ( True ): power[nfactor-1] = power[nfactor-1] + 1 nleft = ( nleft // p ) if ( ( ( abs ( nleft ) ) % p ) != 0 ): break if ( abs ( nleft ) == 1 ): break return nfactor, factor, power, nleft
import prime n = int(input("enter a number")) if (prime.prime(n)): print("Prime") else: print("Not prime")
def test_first_three_primes(self): """Test first three prime numbers""" self.assertEqual(prime(3), [2, 3, 5], msg="First three primes should be [2, 3, 5]")
#!/usr/bin/env python2 from prime import prime_int as prime n = 1 result = 2 while n < 2000000: n += 2 if prime(n): result += n print 'result: %s' % result
def test_for_negative_numbers(self): """Raise value error if the input is negative""" with self.assertRaises(ValueError): prime(-3)
from __future__ import division from prime import prime total, current, primes = 5, 9, 3 i = 4 while primes / total >= 0.1: for __ in range(4): current += i total += 1 if prime(current): primes += 1 i += 2 print(i - 1)
def test_0の時(self): p=prime.prime(0) self.assertEqual(p,False)
#!/usr/bin/python import prime print prime.prime(10000)
def test_negative(self, number=-20): resluts = prime(number) self.assertEqual(resluts, "error")
def test_first_five_primes(self): """Test first five prime numbers""" self.assertEqual(prime(5), [2, 3, 5, 7, 11], msg="First three primes should be [2, 3, 5, 7, 11]")
def test_small_postive_numbers(self, number=2): resluts = prime(number) self.assertTrue(resluts == [2])
def test_for_non_integers(self): """Raise error if the input is not an integer""" with self.assertRaises(TypeError): prime('str')
# -*- coding: utf-8 -*- """Problem 3 02 November 2001 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?""" from prime import prime target=600851475143 factors=[] p=prime() s=target/2 while p.primes[-1]<s: p.add() if target%p.primes[-1]==0: print p.primes[-1]
def test_prime(self) -> None: self.assertEqual(list(prime(13)),[1,2,3,5,7,11,13])
def i4_to_van_der_corput_test(): #*****************************************************************************80 # ## I4_TO_VAN_DER_CORPUT_TEST tests I4_TO_VAN_DER_CORPUT. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 12 May 2015 # # Author: # # John Burkardt # import numpy as np from prime import prime n_prime = 5 n_test = 10 print '' print 'I4_TO_VAN_DER_CORPUT_TEST' print ' I4_TO_VAN_DER_CORPUT computes the elements' print ' of a van der Corput sequence.' print ' The sequence depends on the prime numbers used' print ' as a base.' print '' print ' Bases:' print '' print '' for j in range(1, n_prime + 1): print ' %6d' % prime(j), print '' print '' h = np.zeros(n_prime) for i in range(0, n_test): for j in range(1, n_prime + 1): jm1 = j - 1 p = prime(j) h[jm1] = i4_to_van_der_corput(i, p) print ' %2d' % (i), for j in range(1, n_prime + 1): jm1 = j - 1 print ' %12f' % (h[jm1]), print '' # # Terminate. # print '' print 'I4_TO_VAN_DER_CORPUT_TEST' print ' Normal end of execution.' return
def test_middle_positive_numbers(self, number=20): results = prime(number) self.assertTrue(results == [2, 3, 5, 7, 11, 13, 17, 19])
def test(): numb = input("Enter a number") numb = int(numb) print('Begin in Python') print("Result: ", prime.prime(numb)) print('Back to python')
# A program that returns all palindromic primes between two integers supplied as input (start and end points are included) # Written by: Laene van Niekerk # VNKLAE001 import sys sys.setrecursionlimit (30000) import prime n = eval(input("Enter the starting point N:\n")) m = eval(input("Enter the ending point M:\n")) print("The palindromic primes are:\n", end="") lst = [] # Empty is to append palindromes to def palindrome(primes): # Test to see if the prime number is a palindrome string = str(primes[0]) reverse = string[::-1] if len(primes) == 1: # If there is only one number if string == reverse: lst.append(primes[0]) elif string == reverse: # If the number is a palindrome lst.append(primes[0]) # Appends number to list palindrome(primes[1:]) # Move on to rest of the list else: palindrome(primes[1:]) # If not palindrome, move onto next number list_of_primes = prime.prime(n,m) palindrome(list_of_primes) for i in lst: print(i)
def compute(d): for i in permutations(d): if prime(int(i)): return i return compute(d[1:])