speed up prime number generating - swift

I have written a program that generates prime numbers . It works well but I want to speed it up as it takes quite a while for generating the all the prime numbers till 10000
var list = [2,3]
var limitation = 10000
var flag = true
var tmp = 0
for (var count = 4 ; count <= limitation ; count += 1 ){
while(flag && tmp <= list.count - 1){
if (count % list[tmp] == 0){
flag = false
}else if ( count % list[tmp] != 0 && tmp != list.count - 1 ){
tmp += 1
}else if ( count % list[tmp] != 0 && tmp == list.count - 1 ){
list.append(count)
}
}
flag = true
tmp = 0
}
print(list)

Two simple improvements that will make it fast up through 100,000 and maybe 1,000,000.
All primes except 2 are odd
Start the loop at 5 and increment by 2 each time. This isn't going to speed it up a lot because you are finding the counter example on the first try, but it's still a very typical improvement.
Only search through the square root of the value you are testing
The square root is the point at which a you half the factor space, i.e. any factor less than the square root is paired with a factor above the square root, so you only have to check above or below it. There are far fewer numbers below the square root, so you should check the only the values less than or equal to the square root.
Take 10,000 for example. The square root is 100. For this you only have to look at values less than the square root, which in terms of primes is roughly 25 values instead of over 1000 checks for all primes less than 10,000.
Doing it even faster
Try another method altogether, like a sieve. These methods are much faster but have a higher memory overhead.

In addition to what Nick already explained, you can also easily take advantage of the following property: all primes greater than 3 are congruent to 1 or -1 mod 6.
Because you've already included 2 and 3 in your initial list, you can therefore start with count = 6, test count - 1 and count + 1 and increment by 6 each time.
Below is my first attempt ever at Swift, so pardon the syntax which is probably far from optimal.
var list = [2,3]
var limitation = 10000
var flag = true
var tmp = 0
var max = 0
for(var count = 6 ; count <= limitation ; count += 6) {
for(var d = -1; d <= 1; d += 2) {
max = Int(floor(sqrt(Double(count + d))))
for(flag = true, tmp = 0; flag && list[tmp] <= max; tmp++) {
if((count + d) % list[tmp] == 0) {
flag = false
}
}
if(flag) {
list.append(count + d)
}
}
}
print(list)
I've tested the above code on iswift.org/playground with limitation = 10,000, 100,000 and 1,000,000.

Related

Prime numbers print from range 2...100

I have been assigned with a task to print prime numbers from a range 2...100. I've managed to get most of the prime numbers but can't figure out how to get rid of 9 and 15, basically multiples of 3 and 5. Please give me your suggestion on how can I fix this.
for n in 2...20 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 2 == 1 {
print(n)
} else if n % 3 == 0 && n > 6 {
}
}
This what it prints so far:
2
3
5
7
9
11
13
15
17
19
One of effective algorithms to find prime numbers is Sieve of Eratosthenes. It is based on idea that you have sorted array of all numbers in given range and you go from the beginning and you remove all numbers after current number divisible by this number which is prime number. You repeat this until you check last element in the array.
There is my algorithm which should do what I described above:
func primes(upTo rangeEndNumber: Int) -> [Int] {
let firstPrime = 2
guard rangeEndNumber >= firstPrime else {
fatalError("End of range has to be greater than or equal to \(firstPrime)!")
}
var numbers = Array(firstPrime...rangeEndNumber)
// Index of current prime in numbers array, at the beginning it is 0 so number is 2
var currentPrimeIndex = 0
// Check if there is any number left which could be prime
while currentPrimeIndex < numbers.count {
// Number at currentPrimeIndex is next prime
let currentPrime = numbers[currentPrimeIndex]
// Create array with numbers after current prime and remove all that are divisible by this prime
var numbersAfterPrime = numbers.suffix(from: currentPrimeIndex + 1)
numbersAfterPrime.removeAll(where: { $0 % currentPrime == 0 })
// Set numbers as current numbers up to current prime + numbers after prime without numbers divisible by current prime
numbers = numbers.prefix(currentPrimeIndex + 1) + Array(numbersAfterPrime)
// Increase index for current prime
currentPrimeIndex += 1
}
return numbers
}
print(primes(upTo: 100)) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print(primes(upTo: 2)) // [2]
print(primes(upTo: 1)) // Fatal error: End of range has to be greater than or equal to 2!
what is the Prime num : Prime numbers are the positive integers having only two factors, 1 and the integer itself,
//Funtion Call
findPrimeNumberlist(fromNumber: 1, toNumber: 100)
//You can print any range Prime number using this fucntion.
func findPrimeNumberlist(fromNumber:Int, toNumber: Int)
{
for i in fromNumber...toNumber
{
var isPrime = true
if i <= 1 { // number must be positive integer
isPrime = false
}
else if i <= 3 {
isPrime = true
}
else {
for j in 2...i/2 // here i am using loop from 2 to i/2 because it will reduces the iteration.
{
if i%j == 0 { // number must have only 1 factor except 1. so use break: no need to check further
isPrime = false
break
}
}
}
if isPrime {
print(i)
}
}
}
func getPrimeNumbers(rangeOfNum: Int) -> [Int]{
var numArr = [Int]()
var primeNumArr = [Int]()
var currentNum = 0
for i in 0...rangeOfNum{
currentNum = i
var counter = 0
if currentNum > 1{
numArr.append(currentNum)
for j in numArr{
if currentNum % j == 0{
counter += 1
}
}
if counter == 1{
primeNumArr.append(currentNum)
}
}
}
print(primeNumArr)
print(primeNumArr.count)
return primeNumArr
}
Then just call the function with the max limit using this
getPrimeNumbers(rangeOfNum: 100)
What is happening in above code:
The numArr is created to keep track of what numbers have been used
Any number that is prime number is added/appended to primeNumArr
Current number shows the number that is being used at the moment
We start from 0 ... upto our range where we need prime numbers upto (with little modification it can be changed if the range starts from other number beside 0)
Remember, for a number to be Prime it should have 2 divisor means should be only completely divisible by 2 numbers. First is 1 and second is itself. (Completely divisible means having remainder 0)
The counter variable is used to keep count of how many numbers divide the current number being worked on.
Since 1 is only has 1 Divisor itself hence its not a Prime number so we start from number > 1.
First as soon as we get in, we add the current number being checked into the number array to keep track of numbers being used
We run for loop to on number array and check if the Current Number (which in our case will always be New and Greater then previous ones) when divided by numbers in numArr leaves a remainder of 0.
If Remainder is 0, we add 1 to the counter.
Since we are already ignoring 1, the max number of counter for a prime number should be 1 which means only divisible by itself (only because we are ignoring it being divisible by 1)
Hence if counter is equal to 1, it confirms that the number is prime and we add it to the primeNumArr
And that's it. This will give you all prime numbers within your range.
PS: This code is written on current version of swift
Optimised with less number of loops
Considered below conditions
Even Number can not be prime number expect 2 so started top loop form 3 adding 2
Any prime number can not multiplier of even number expect 2 so started inner loop form 3 adding 2
Maximum multiplier of any number if half that number
var primeNumbers:[Int] = [2]
for index in stride(from: 3, to: 100, by: 2) {
var count = 0
for indexJ in stride(from: 3, to: index/2, by: 2) {
if index % indexJ == 0 {
count += 1
}
if count == 1 {
break
}
}
if count == 0 {
primeNumbers.append(index)
}
}
print("primeNumbers ===", primeNumbers)
I finally figured it out lol, It might be not pretty but it works haha, Thanks for everyone's answer. I'll post what I came up with if maybe it will help anyone else.
for n in 2...100 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 3 == 0 && n > 6 {
} else if n % 5 == 0 && n > 5 {
} else if n % 7 == 0 && n > 7{
} else if n % 2 == 1 {
print(n)
}
}

Why is year returning value of 1 when it should be increasing with each loop?

If a flower grows 1cm every year, how long will it take to be 15.24cm?
var year = 0
var length = 0.0
while length <= 15.24 {
if length.truncatingRemainder(dividingBy: 1.0) == 0 {
year += 1
}
length += 0.01
}
print(year)
My approach:
Year increments by 1 each time the length is a whole number (because rate is 1cm/year)
Goal is to calculate how long it'll take to be fully grown (15.24cm)
Year should return 15
Why's it only returning 1?
An example of scaled Int:
var year = 0
var length: Int = 0_00 //1_00 represents 1.00 cm
while length <= 15_24 {
if length % 1_00 == 0 {
year += 1
}
length += 0_01
}
print(year) //-> 16
(Underscores (_) are ignored in Swift numeric literals, it's added just for readability.)
Seems you need to modify a little bit, if you expect 15.

stress centrality in social network

i got the error of this code which is:
path[index][4] += 1
IndexError: list index out of range
why this happened?how can i remove this error ?
Code:
def stress_centrality(g):
stress = defaultdict(int)
for a in nx.nodes_iter(g):
for b in nx.nodes_iter(g):
if a==b:
continue
pred = nx.predecessor(G,b) # for unweighted graphs
#pred, distance = nx.dijkstra_predecessor_and_distance(g,b) # for weighted graphs
if a not in pred:
return []
path = [[a,0]]
path_length = 1
index = 0
while index >= 0:
n,i = path[index]
if n == b:
for vertex in list(map(lambda x:x[0], path[:index+1]))[1:-1]:
stress[vertex] += 1
if len(pred[n]) >i:
index += 1
if index == path_length:
path.append([pred[n][i],0])
path_length += 1
else:
path[index] = [pred[n][i],0]
else:
index -= 1
if index >= 0:
path[index][4] += 1
return stress
Without the data it's hard to give you anything more than an indicative answer.
This line
path[index][4] += 1
assumes there are 5 elements in path[index] but there are fewer than that. It seems to me that your code only assigns or appends to path lists of length 2. As in
path = [[a,0]]
path.append([pred[n][i],0])
path[index] = [pred[n][i],0]
So it's hard to see how accessing the 5th element of one of those lists could ever be correct.
This is a complete guess, but I think you might have meant
path[index][1] += 4

Count number of repeats in Swift

I want to know how am I supposed to count the number of time a loop has repeated itself? More specifically how do I extract and output the number of repeats?
var x = 20
while x < 100 {
x += 10
}
The loop has executed 8 times in order to get x == 100. Is there a way to extract the number '8' so it can be used somewhere else (e.g. to make it a variable elsewhere)?
You said it yourself: you want to count. So count!
var x = 20
var numtimes = 0
while x < 100 {
x += 10
numtimes += 1 // count!
}
numtimes // 8

simple loop in coffeescript

I have this code:
count = $content.find('.post').length;
for x in [1...count]
/*
prev_el_height += $("#content .post:nth-child(" + x + ")").height();
*/
prev_el_height += $content.find(".post:nth-child(" + x + ")").height();
I expected this to turn into
for (x = 1; x < count; x++) { prev_el ... }
but it turns into this:
for (x = 1; 1 <= count ? x < count : x > count; 1 <= count ? x++ : x--) {
Can somebody please explain why?
EDIT: How do I get my expected syntax to output?
In CoffeeScript, you need to use the by keyword to specify the step of a loop. In your case:
for x in [1...count] by 1
...
You're asking to loop from 1 to count, but you're assuming that count will always be greater-than-or-equal-to one; the generated code doesn't make that assumption.
So if count is >= 1 then the loop counter is incremented each time:
for (x = 1; x < count; x++) { /* ... */ }
But if count is < 1 then the loop counter is decremented each time:
for (x = 1; x > count; x--) { /* ... */ }
Well, you want x to go from 1 to count. The code is checking whether count is bigger or smaller than 1.
If count is bigger than 1, then it has to increment x while it is smaller than count.
If count is smaller than 1, then it has to decrement x while it is bigger than count.
For future reference:
$('#content .post').each ->
prev_el_height += $(this).height()
Has the same effect, assuming :nth-child is equivalent to .eq(), and x going past the number the elements is a typo.