J
J
jestev2017-10-12 16:41:05
C++ / C#
jestev, 2017-10-12 16:41:05

How to combine random filling of an array and searching for a prime number in it?

There is a program in which there is a function for searching for prime numbers. If everything is extremely simple with one number, then how to look for prime numbers in an array? Here is the code. I know that the function is wrong, but what needs to be changed so that there is a search for a prime number in the array?

#include "stdafx.h"
#include <iostream> 
#include <cstdlib>
#include <ctime>
using namespace std;

int is_prime(int a[5])
{
  
  if (a[5] == 1) return 1;
  int number = 0;
  for (int i = 2; i <= a[5]; i++)
    if (a[5] %i == 0) number++;
  if (number == 1) return 1;
  else return 0;
}

int main()
{
  srand(time(NULL));
  int a[5];
  for (int k = 0; k < 5; k++) {
    a[k] = rand() % 21;
    cout << a[k] << "\n";
  }
  int c = is_prime(a);
    if (c == 1) cout << "is prime";
  else cout << "is not prime";
    return 0;
  system("pause");
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2017-10-12
@res2001

1. You should have 2 nested loops in is_prime: 1 loop over the array elements, the second (nested) from 2 to a[i] - checking for a prime number. Now - only one and that one is not correct (due to indexing).
2.And deal with array indexing, it looks like you don't understand what you are doing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question