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;
}
Comments