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

Program: Twin Primes Please help complete the program below in C language. Two n

ID: 3603588 • Letter: P

Question

Program: Twin Primes

Please help complete the program below in C language.

Two numbers are called twin primes if both numbers are prime numbers and their difference is 2. For example, 3 and 5 are twin primes, as are, 11 and 13.

Write a C program that prints out all twin primes between 1 and, say n.

The value of n is a positive integer that comes in from argv[1].

For example:

3 and 5 are twin primes.

5 and 7 are twin primes.

11 and 13 are twin primes.

17 and 19 are twin primes.

29 and 31 are twin primes.

41 and 43 are twin primes.

59 and 61 are twin primes.

71 and 73 are twin primes.

Remember, a call to the function malloc reserves unnamed space on the HEAP. If the call works, it returns the address of the first byte reserved. The type of this address is a pointer to void. This type needs to be cast by the programmer if there is to be peace in the world.

Explanation / Answer

/************************************TwinPrimes.c************************************/

#include<stdio.h>

#include<stdlib.h>

#include<malloc.h>

int main(int argc, char* argv[])

{

//variable declaration

int i,j,count,num,elem=0;

int *arr;

// converting char array first argument to int

num=atoi(argv[1]);

// creating dynamic array of num size

arr = (int*) malloc(num * sizeof(int));

// loop for checking for primes

for(i=3;i<num;i++)

{

count = 0;

for(j=2;j<i;j++)

{

if(i%j == 0)

{

count++;

}

}

if(count==0)

{

arr[elem] = i;

elem++;

}

}

// Checking twin primes if available then printing them

for(i=1;i<elem;i++)

{

if(arr[i] == arr[i-1] +2)

{

printf("%d and %d are twin primes. ",arr[i-1],arr[i]);

}

}

// free array memory

free(arr);

return 0;

}

/*********************************output**********************************/

C:UserslmaliDesktopChegg>g++ TwinPrimes.c

C:UserslmaliDesktopChegg>a.exe 100
3 and 5 are twin primes.
5 and 7 are twin primes.
11 and 13 are twin primes.
17 and 19 are twin primes.
29 and 31 are twin primes.
41 and 43 are twin primes.
59 and 61 are twin primes.
71 and 73 are twin primes.

Thanks a lot. Please let me know if you have any doubt.