+ 2
write a program to read an integer array with five elements and print the prime and not prime numbers of it? Thanks first for answers 😊
7 Respostas
+ 8
Ehy @Filip why so complicated ?
I am not even sure that will work in code playground.
Here there is a simpler one:
int main() {
int foo[5] = {49, 8, 5, 202, 13}; .
for (int i=0; i<5; i++)
{
bool prime=true;
for (int j=2; j*j<=foo[i]; j++)
{
if (foo[i] % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << foo[i] << " ";
}
return 0;
}
I saved it in my codes so I could add comments. To see comments:
https://www.sololearn.com/Profile/2981791
Remember keep it simple :)
Ah if you want to print not prime numbers just change last if statemente to if(!prime).
+ 6
#include <stdio.h>
#include <stdlib.h>
unsigned prime(int n) {
for(int i=2; i<=n/2; i++) {
if(n%i==0)
return 0;
return 1;
}
}
void main() {
int a[5], b[5], c[5], n, i, m=0, k=0;
do scanf("%d", &n); while(n<=0 || n>5);
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=0; i<n; i++) {
if(prime(a[i]) && a[i]>=2)
b[k++] = a[i];
if(!prime(a[i]))
c[m++] = a[i];
}
printf("Prime: ");
for(i=0; i<k; i++)
printf("%d ", b[i]);
printf("\nNon prime: ");
for(i=0; i<m; i++)
printf("%d ", c[i]);
system("pause");
}
Here you go! :D
+ 6
Okayy, I guess you know better, I am just a begginer, and that's what I came up with. And it works, I tried it in VS
+ 6
I don't like this code playground, programs written in C don't work, but yeah, learning is the key to success. Isn't it?
+ 5
This will not run in here, but It will on any other compiler, keep in mind that this is written in C
+ 3
Your answer is still valid ! Just not good for code playground and a bit complicated in my opinion. From that code it looks like you know better than me haha We are all learning here.
+ 1
This code would help you: given a few values in a vector it prints only the prime numbers..
To test if a number is prime you assume that is divisible only by 1 and itself.
#include <iostream>
using namespace std;
bool isPrime(int x) {
if (x<=0) return false; // i don't test those values
if (x<2) return true; // 1 and 2 are primes!
for (int i=2;i<x;i++) {
if (x%i==0) return false;
}
return true;
}
int main() {
int a[5]={10,11,12,13,14}; // a set of values
for (int i=0;i<5;i++) {
if (isPrime(a[i])) // here is the condition
cout<<a[i]<<endl;
}
return 0;
}