ronith
10/25/2018 - 12:33 PM

Consecutive primes

Given an array of numbers, find the length of longest subarray having only prime numbers.

//https://lh3.googleusercontent.com/mixhufW0fe3sWdXAYmR7IR9U6MeFCvXmfEksdcmwKlTjoJcOq_pL2jLiRFiaWk0Ou2r1eYUtSDJOtUmZTQRTju0egK-3hdQUPmeSlp8-kxcuiqpLMtNeGwoXQNJZuJ1SatMVMGpo
#include <bits/stdc++.h>
using namespace std;

//https://www.geeksforgeeks.org/primality-test-set-1-introduction-and-school-method/
bool isPrime (int n) {// func to check if a number is prime
    if (n<= 1)
        return 0;
    if (n<=3)
        return 1;
    if (n%2==0 || n%3==0)
        return 0;

    for (int i=5;i*i<=n;i+=6)
        if (n%i==0 || n%(i+2)== 0)
            return 0;
    return 1;
}

int main() {
    int n;
    cin>>n;
    int a[n];
    for (int i=0;i<n;i++)
        cin>> a[i];

    set <int> s;//set to store the prime numbers in the array
    int c=0, m=0;
    for (int i=0;i<n;i++) {
        int p= a[i];
        if ((s.find(a[i])!=s.end()) || isPrime(a[i])) {
            s.insert(a[i]);
            c++;
            if (m<c)
                m=c;
        }
        else
            c=0;
    }
    cout<< m;
}