Question #37470

Exercise 3: Prime numbers
Write a program that prompts the user to enter two positive integers m and n where m < n then
output all prime numbers in the range m and n, inclusive. You must write a function that would test
a number whether it is prime.
1

Expert's answer

2013-12-05T09:37:34-0500

Answer on Question#37470 - Programming, C++

1. Exercise 3: Prime numbers

Write a program that prompts the user to enter two positive integers m and n where m <; n then output all prime numbers in the range m and n, inclusive. You must write a function that would test a number whether it is prime.

Solution.


#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
int isSimple(int n)
{
    if (n == 1 || n <= 0)
        return 0;
    for (int i = 2; i <= n/2; ++i)
        if (n % i == 0)
            return 0;
    return 1;
}
int main(int argc, char * argv[])
{
    int N, M;
    int * Arr;
    printf("Enter M: ");
    scanf("%d", &M);
    printf("Enter N: ");
    scanf("%d", &N);
    Arr = (int*) malloc(N * sizeof(int));
    int j = 0;
    for (int i = M; i < N; ++i, j++)
    {
        Arr[j] = i;
    }
    int simple_cnt = 0;
    printf("number of primes: \n");
    for (int i = 0; i < j; ++i)
    {
        if (isSimple(Arr[i]) == 1)
        {
            printf("%d", Arr[i]);
            ++simple_cnt;
        }
    }
    printf("\nThe number of prime numbers in the sequence: %d\n", simple_cnt);
    free(Arr);
    system("pause");
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS