Thursday, May 7, 2009

Print all prime number upto a certain Range in C++ and Python

I have tried developing in C++ and Python. I like scripting in python and C++ is my favorite programming language.


#!/usr/bin/env python




#Author : Ronak Patel

#Date : 05/07/2009

#Purpose : Write a script to get all prime numbers upto a certain range.



x = int(raw_input("Enter the range: "))

for i in range(2,x):

isprime = 1

for j in range(2,i):

if(i==j):

continue

elif(i%j==0):

isprime=0

if(isprime):

print "%d\t" % i




The logic is the same but only the syntax is different. Here we have two for loops. The first one starts from 2 and goes till the last number you want. The other loop starts with a 2 and end with the first loop digit. So we make sure all the numbers are verified. Let me explain you in a bit detail.

In the above script, Initially i will be 2 and j will also be 2. It will end up exiting the loop because it satisfies the condition i==j and it will be printed since isprime remains 1. Secondly i will be 2 and j will be 3 which wont satisfy the condition i==j and also i%j==0. So it will move forward with i=3 and j=3 which then shows that it is also a prime number.

Now when i=2 and j=4, it satisfies the condition i%j==0 which means it will not be printed since isprime=0. So this is how this works.

Below is the C++ implementation.


// prime.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include


//using namespace std;

void prime(int a)
{
int isprime;

for(int i=2;i<=a;i++)
{
printf("i in the first loop %d\n", i);
isprime =1;
for(int j =2;j<=i;j++)
{
printf("\tj in the second loop %d\n", j);

if(i==j)
{
continue
;
}
else if (i %j == 0)
isprime = 0;
}
if(isprime)
printf("%d\n",i);
}
getchar(); }
void main()
{
int n;
std::cout<<"Enter range: ";
std::cin >> n;

prime(n);

getchar();

}


Hope this helps. I will try and post Perl script too for this. I believe I did not find more implementations of this particular program. You can find many implementations for odd even programs but not prime ones.


Here goes the perl script for the same purpose


#!/usr/bin/perl -w
#use strict;
#Author : Ronak Patel
#Date : 05/07/2009
#Purpose : Write a script in perl to print all prime numbers

print("Enter the range: ");
my $max = <>;
chomp($max);
$i = 0;
$j =0;
$isprime = 0;


for($i = 2;$i <= $max; $i++) { $isprime=1; for($j = 2; $j <= $i; $j++) { if($i == $j){} # continue; elsif($i%$j==0) { $isprime = 0; } } if($isprime) { print("$i\n"); } }

No comments: