#!/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++)
continue
Here goes the perl script for the same purpose
#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:
Post a Comment