Skip to content

Instantly share code, notes, and snippets.

@alexanderscott
Created September 14, 2012 15:28
Show Gist options
  • Save alexanderscott/3722639 to your computer and use it in GitHub Desktop.
Save alexanderscott/3722639 to your computer and use it in GitHub Desktop.
Multi-language functions for displaying prime numbers
###
# scala
##
object P extends App{
def c(M:Int)={
val p=collection.mutable.BitSet(M+1)
p(2)=true
(3 to M+1 by 2).map(p(_)=true)
for(i<-p){
var j=2*i;
while(j<M){
if(p(j))p(j)=false
j+=i}
}
p
}
val i=args(0).toInt
println(c(((math.log(i)*i*1.3)toInt)).take(i).mkString("\n"))
}
##
# C
##
#include<conio.h>
#include<iostream.h>
void main()
{
clrscr();
int a,b,c;
cout<<2<<"\t";
for(a=3;a<=100;a=a+2)
{
for(b=2;b<=sqrt(a);b++)
{
if(a%b!=0)
cout<<a<<"\t";
else
cout<<"-\t";
}
}
getch();
}
##
# Java
##
import java.util.Scanner;
public class PrimeNumberExample {
public static void main(String args[]) {
System.out.println("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
for(int number = 2; number<=limit; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
##
# Python
##
N=15485864
a=[1]*N
x=xrange
for i in x(2,3936):
if a[i]:
for j in x(i*i,N,i):a[j]=0
print [i for i in x(len(a))if a[i]==1][2:]
# JavaScript
bool is_prime(int x)
{
if(x <= 1)
return false;
int s = (int) sqrt(x);
for(int i = 2; i <= s; i++)
if(x%i == 0)
return false;
return true;
}
##
# Ruby
##
def is_prime(n)
return false if n <= 1
2.upto(Math.sqrt(n).to_i) do |x|
return false if n%x == 0
end
true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment