Skip to content

Instantly share code, notes, and snippets.

@iambibhas iambibhas/Result
Created Aug 24, 2012

Embed
What would you like to do?
Find Prime Number in Given Range
#include <stdio.h>
#include <time.h>
#define MAX 100000
int main(){
int primeNumbers[MAX];
int i, j;
int divisible=0;
int count = 1;
primeNumbers[0] = 2;
clock_t start = clock();
for(i=2;i<=MAX;i++){
divisible = 0;
for(j=0;j<count;j++){
// for slots in prime number
if(i % primeNumbers[j] == 0)
divisible = 1;
}
if(divisible == 0){
primeNumbers[count] = i;
count++;
}
}
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
printf("======\nC\n======\n%f seconds\n%d primes\n", seconds, count);
}
<?php
set_time_limit(1000);
function a(){
$primeNumbers = array();
for ($i = 2; $i < 100000; $i++)
{
$divisible = false;
foreach ($primeNumbers as $number)
{
if ($i % $number == 0)
{
$divisible = true;
break;
}
}
if ($divisible == false)
{
$primeNumbers[] = $i;
}
}
return $primeNumbers;
}
echo "======\n";
echo "PHP\n";
echo "======\n";
$tt=mfl();
$resp = a();
echo mfl()-$tt . " seconds\n";
echo count($resp) . " primes\n";
function mfl() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
import time
def a():
primeNumbers = []
for i in range(2, 100000):
divisible = False
for number in primeNumbers:
if i % number == 0:
divisible = True
break
if divisible == False:
primeNumbers.append(i)
return primeNumbers
print '======'
print 'Python'
print '======'
tt = time.time()
resp = a()
print time.time() - tt, 'seconds'
print len(resp), 'primes'
bibhas@bibhas-CQ42:~/Works/langtest$ php php.php && python python.py && gcc c.c && ./a.out
======
PHP
======
5.5071251392365 seconds
9592 primes
======
Python
======
4.45425796509 seconds
9592 primes
======
C
======
2.640000 seconds
9592 primes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.