Code archives/Algorithms/Twin Primes
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
I had a assembly programming assignment that was to print out the first 100 twin primes. So I made this mock up program to figure how a easy method for calculating twin primes. It does in fact work, but now I need to translate it into assembly :( | |||||
Rem ********************************************************** twin primes by daniel wooden ********************************************************** End Rem Local count:Int = 1 Local curnum:Int = 3 Local a:Int = 0 Local b:Int = 0 While count < 101 ' <-- twin primes upto the 100th place. If IsPrime( curnum ) And IsPrime( curnum+2 ) Then a = curnum b = curnum+2 Print "Twin Prime Set: " + count + " (" + a + "," + b + ")" count :+ 1 End If curnum :+ 1 Wend End Function IsPrime:Int( Num:Int ) Local Prime:Int = True For i = 2 To Num/2 If (Num Mod i) = 0 Then Prime = False End If Next Return Prime End Function |
Comments
| ||
Your calculating the even numbers too, try curnum :+ 2, should go twice as fast. |
| ||
To make IsPrime faster you should use 'Exit' after 'Prime = False' because you're still in the 'For-Next' loop when using large numbers. |
| ||
compatible without blitzmax:;********************************************************** ;twin primes by daniel wooden ;converted by shadowturtle ;********************************************************** Local count = 1 Local curnum = 3 Local a = 0 Local b = 0 While count < 101 If IsPrime( curnum ) And IsPrime( curnum+2 ) Then a = curnum b = curnum+2 Print "Twin Prime Set: " + count + " (" + a + "," + b + ")" count = count + 1 End If curnum = curnum + 1 Wend WaitKey End Function IsPrime( Num ) Local Prime = True For i = 2 To Num/2 If (Num Mod i) = 0 Then Prime = False End If Next Return Prime End Function |
Code Archives Forum