Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1 Problem 1 Create a program that generates a file of all the prime numbers less

ID: 3697893 • Letter: 1

Question

1 Problem 1 Create a program that generates a file of all the prime numbers less than a number N taken from command line. It is up to you how you store this data into the file as long as your next problem can read it. Your program should work for numbers up to 100,000. You must implement the Sieve of Eratosthenes in order to generate this file. You are welcome to take a look at the wikipedia source on this which even includes some pseudocode https://en.wikipedia.org/ wiki/Sieve_of_Eratosthenes

Example input: 10

Example output in ‘‘file.txt’’:

2 3 5 7 2

Problem 2 Create a program that takes a file of prime numbers generated from Problem 1 and stores them in any way of your choosing. The user may query the program as many times as they would like and it will output whether or not the number given is prime. The queries must run in log(n) time where n is the amount of prime numbers in the file. If the number that is entered is negative stop the program. If the number is greater than the largest in the file inform the user that they need a file which contains more prime numbers.

Example input in ‘‘file.txt’’: 2 3 5 7

Example command line interaction with user: Enter a number. 3 3 is a prime number. Enter another number.

4

4 is not a prime number. Enter another number. 8

Current file not large enough for 8.

Enter another number. -1

Bye.

Explanation / Answer

Answer 1->

#include <stdio.h>
#!/usr/bin/perl


#define LIMIT 1500000 /*size of integers array*/

#define PRIMES 100000 /*size of primes array*/

int main(){
int i,j,numbers[LIMIT];
int primes[PRIMES];

/*fill the array with natural numbers*/
for (i=0;i<limit;i++){
numbers[i]=i+2;
}

/*sieve the non-primes*/
for (i=0;i<limit;i++){
if (numbers[i]!=-1){
for (j=2*numbers[i]-2;j<limit;j+=numbers[i])
numbers[j]=-1;
}
}

/*transfer the primes to their own array*/
j = 0;
for (i=0;i<limit&&j<primes;i++)
if (numbers[i]!=-1)
primes[j++] = numbers[i];

/*print*/
for (i=0;i<primes;i++)
printf("%dn",primes[i]);


$variable = "primes[i]";
for($j=0; $j<i;$j++)
{
$variable++;
$file.txt = $variable."."."txt";
open output,">$file.txt"
printf("%dn", $file.txt);


return 0;

}
  
}


Answer 2->

#include <stdio.h>
#!/usr/bin/perl -w

int num;


# declare your variables
my $varfile = "$file.txt";


# open the file
open DATA, $varFile $!";
while (<DATA>)
{
# chomp the line
chomp;

printf(" Enter the number");
scanf("%d", &num);   

if (num ==DATA)
printf(" The given number is prime,%d, &num);

else
  
printf(" The given number is not prime,%d, &num");

else if (num==-1)

printf(" bye Bye");
}