Prime Numbers in IronPython QuickStart Sample
Illustrates working with prime numbers and the IntegerMath class in the Numerics.NET namespace in IronPython.
This sample is also available in: C#, Visual Basic, F#.
Overview
This QuickStart sample demonstrates how to work with prime numbers using the IntegerMath class from Numerics.NET. The sample shows essential operations for working with prime numbers and factorization.
The sample illustrates several key capabilities:
- Factoring integers into their prime components, including handling of repeated factors
- Testing numbers for primality using the IsPrime method
- Finding the next prime number greater than a given value
- Finding the previous prime number less than a given value
- Working with large numbers up to 48 bits in length
The code demonstrates practical applications like:
- Decomposing composite numbers into their prime factors with multiplicity
- Verifying whether large numbers are prime
- Generating sequences of consecutive prime numbers both forward and backward
- Handling edge cases with large integers and repeated factors
All operations use efficient algorithms optimized for performance while maintaining numerical accuracy.
The code
import numerics
# We use many classes from the Extreme.Mathematics.SpecialFunctions
# namespace.
from Extreme.Mathematics import *
# Illustrates working with prime numbers using the
# IntegerMath class in the Extreme.Mathematics.SpecialFunctions
# namespace of Extreme Numerics.NET.
#
# Factoring numbers
#
n = 1001110110
factors = IntegerMath.Factorize(n)
print "{0} = {1}".format(n, factors[0]),
for index in range(1, factors.Length):
print " *", factors[index],
print
# Factors that occur multiple times is repeated as many times as necessary:
n = 256 * 6157413
factors = IntegerMath.Factorize(n)
print "{0} = {1}".format(n, factors[0]),
for index in range(1, factors.Length):
print " *", factors[index],
print
# The 64bit version can safely factor numbers up to 48 bits long:
n = 1296523 * 1177157
factors = IntegerMath.Factorize(n)
print "{0} = {1}".format(n, factors[0]),
for index in range(1, factors.Length):
print " *", factors[index],
print
#
# Prime numbers
#
# The IsPrime method verifies if a number is prime or not.
n = 801853937
print n, "is prime?", IntegerMath.IsPrime(n), "!"
n = 801853939
print n, "is prime?", IntegerMath.IsPrime(n), "!"
# MextPrime gets the first prime after a specified number.
# You can call it repeatedly to get successive primes.
# Let#s get the 10 smallest primes larger than one billion:
n = 1000000000
print "\nFirst 10 primes greater than 1 billion:"
for index in range(0,10):
n = IntegerMath.NextPrime(n)
print "{0:15}".format(n),
print
# PreviousPrime gets the last prime before a specified number.
n = 1000000000
print "Last 10 primes less than 1 billion:"
for index in range(0,10):
n = IntegerMath.PreviousPrime(n)
print "{0:15}".format(n),
print