Sum of prime numbers in array - c

I need to input from keyboard some random values and put them in an array. After that I need to print the average of the prime numbers only. This is my code but it doesn't work:
#include<stdio.h>
#include<conio.h>
int main()
{
int v[50], n, i, nrprim = 0, sum = 0, j;
float medie = 0;
printf("dati numarul de elemente al vectorului:\t");
scanf("%d", &n);
for ( i = 0; i < n; i++)
{
printf("dati elmentele vectorului:\t");
scanf("%d", &v[i]);
}
for(i=0; i<n; i++)
for(j=2; j<v[i]; j++)
{
if(v[i]%j!=0)
{
sum = sum + v[i];
nrprim++;
}
}
medie =( sum/nrprim);
printf("%f", medie);
_getch();
return 0;
}

You're adding to sum and nrprim every time you find a number that isn't a factor of it. For instance, when i == 8, you'll add to them when j is 3, 5, 6, or 7.
A number is only prime if none of the numbers below it are factors. You have to wait until the end of the j loop to know this.
And if you want fractions in the average, you need to convert one of the values to float before dividing. Otherwise you get integer division.
#include<stdio.h>
#include<conio.h>
int main()
{
int v[50], n, i, nrprim = 0, sum = 0, j;
float medie = 0;
printf("dati numarul de elemente al vectorului:\t");
scanf("%d", &n);
for ( i = 0; i < n; i++)
{
printf("dati elmentele vectorului:\t");
scanf("%d", &v[i]);
}
for(i=0; i<n; i++)
int is_prime = 1;
for(j=2; j<v[i]; j++)
{
if(v[i]%j == 0)
{
is_prime = 0;
break;
}
}
if (is_prime) {
sum = sum + v[i];
nrprim++;
}
medie = float(sum)/nrprim;
printf("%f", medie);
_getch();
return 0;
}

Your prime check is wrong. Instead of testing whether a number can't be divided by any other number, you're considering a number a prime when you find the first number that you can't divide it by. So when you for instance test if 9 is prime, you say "yes" because it couldn't be divided by 2, without checking if it can be divided by 3. Try something like this instead:
int flag;
for (i = 0; i < n; i++)
{
flag = 1;
for (j = 2; j < v[i]; j++)
{
if (v[i] % j == 0)
{
flag = 0;
break;
}
}
if (flag) {
sum = sum + v[i];
nrprim++;
}
}
Also, your program crashes if no prime number is entered, so you need to handle that case as well. I would suggest something such as:
if (nrprim) {
medie = (sum / nrprim);
printf("%f\n", medie);
}
else {
printf("Error: no prime numbers were entered.\n");
}

Related

The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k

I want to write a program where a user tells me an integer(n) and i calculate The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k.
Ive made a function which does that But the sum is never correct. For example for n=2 it should be sum=0 but shows sum=-1 for n=3 should be sum=+2 but i shows sum=3. (Ignore the debugging printfs)
#include <stdio.h>
int athroismaAkolouthias(int n); // i sinartisi me tin opoia ypologizete to athroisma akolouthias 1+(1-2)+(1-2+3)+(1-2+3-4).....
int main(){
int n;
printf("give n: ");
scanf("%d", &n);
printf("the sum is %d", athroismaAkolouthias(n));
}
int athroismaAkolouthias(int n){
int sum1=0, sum2=0,sum=0;
int i, temp, j;
for (i=1; i<=n; i++){
for (j=1; j<=i; j++){
temp=j;
}
if (i%2==0){sum=sum-temp; printf("test1 %d%d",sum,temp);}
else{sum=temp; printf("test2 %d%d",sum,temp);}
}
return sum;
}
Your issue is with our loop which iterate with j, it should update the inner_sum based on j even/odd condition as follows:
#include <stdio.h>
int akl(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
int inner_sum = 0;
for (int j = 1; j <= i; j++) {
if (j % 2 == 0) {
inner_sum -= j;
} else {
inner_sum += j;
}
}
sum += inner_sum;
}
return sum;
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", akl(n));
}
You only need two variables for sum that I named them inner_sum and sum which shows the sum of each term and sum over all terms.
Suspicious Line: else {sum = temp; ...
Shouldn't you be adding or subtracting to sum every time??
Why are you assigning to it here, without an addition or subtraction?
You also have variables sum, sum1, and sum2.
You print sum1 and sum2, but never modify them.
Here's my solution:
// The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)... where even integers are -k and odd integers are +k.
#include <stdio.h>
int ancho(int n)
{
int sum=0;
for(int i=1; i<=n; ++i)
{
for(int j=1; j<=i; ++j)
{
sum += (2*(j%2)-1)*j;
}
}
return sum;
}
int main(void)
{
int n = 5;
printf("Solution is %d\n", ancho(n));
}
// Solution is 3 for n = 5,
// because: 1 + (1-2) + (1-2+3) + (1-2+3-4) + (1-2+3-4+5) =
// 1-1+2-2+3 = 3
Output
Success #stdin #stdout 0s 5476KB
Solution is 3
IDEOne Link

Finding the highest frequency of an array and all elements which have that frequency

I'm asked to find the highest frequency from an array of elements and all elements with said frequency. My code seem to work just fine but it seems to have a mistake somewhere when i submit it. Can anyone help me find the error?
Format Input:
The first line contains an integer T stating the number of test cases. For each test case, the first line contains a single integer N which indicate the number of element in the array. The next line contains N integers Xi (1≤i≤N) which indicate ith element in the array.
Format Output:
Consists of T lines where each line has the format “Case #X: Y ”, where X is the test case number starting at 1 and Y is the highest frequency. Next line contains all elements which have that frequency sorted in ascending order.
Constraints:
1 ≤ T ≤ 20 | 2 ≤ N ≤ 20.000 | 1 ≤ Xi ≤ 2 × 10^5
Sample Input:
3
8
1 1 2 2 3 4 5 5
8
5 5 4 3 2 2 1 1
4
1 1 1 3
Sample Output:
Case #1: 2
1 2 5
Case #2: 2
1 2 5
Case #3: 3
1
Here is my code:
#include <stdio.h>
int main() {
int T, N[20];
scanf("%d", &T); getchar();
int A[T][20000];
for (int i = 0; i<T; i++) {
scanf("%d", &N[i]); getchar();
for (int j = 0; j<N[i]; j++) {
scanf("%d", &A[i][j]); getchar();
}
int X = 0;
for (int j = 0; j<N[i]; j++) {
for (int k = j + 1; k<N[i]; k++) {
if (A[i][k]<A[i][j]) {
X = A[i][j];
A[i][j] = A[i][k];
A[i][k] = X;
}
}
}
}
int f[20000];
for (int i = 0; i<T; i++) {
int c = 0, mc = 0;
for (int j = 0; j<N[i]; j++) {
c = 1;
if(A[i][j] != -1) {
for (int k = j+1; k<N[i]; k++) {
if (A[i][j] == A[i][k]) {
c++;
A[i][k] = -1;
}
}
f[j]=c;
}
if (c>mc) {
mc = c;
}
}
printf("Case #%d: %d\n", i+1, mc);
for (int j = 0; j<N[i]; j++) {
if (A[i][j] != -1) {
if (f[j] == mc) {
printf ("%d", A[i][j]);
if (j<N[i]-1) {
printf(" ");
}
}
}
}
printf("\n");
}
return 0;
}
EDIT
So I made another code where instead of inputting all arrays at once and outputting everything at once, this code outputs the frequency and elements after i input the first arrays of numbers. But it seems like the code still have problems and i can't find where... P.s I'm pretty new to this, so i apologise for the lack of efficiency of my codes.
NEW CODE
#include <stdio.h>
int main() {
int T, N;
scanf("%d", &T); getchar();
int A[20000];
for (int i = 0; i<T; i++) {
scanf("%d", &N); getchar();
for (int j = 0; j<N; j++) {
scanf("%d", &A[j]); getchar();
}
int X;
for (int j = 0; j<N; j++) {
for (int k = j + 1; k<N; k++) {
if (A[k]<A[j]) {
X = A[j];
A[j] = A[k];
A[k] = X;
}
}
}
int f[N], c = 0, mc = 0;
for (int j = 0; j<N; j++) {
c = 1;
if(A[j] != -1) {
for (int k = j+1; k<N; k++) {
if (A[j] == A[k]) {
c++;
A[k] = -1;
}
}
f[j]=c;
if (c>mc) {
mc = c;
}
}
}
printf("Case #%d: %d\n", i+1, mc);
for (int j = 0; j<N; j++) {
if (A[j] != -1) {
if (f[j] == mc) {
printf ("%d", A[j]);
if (j<N-1) {
printf(" ");
}
}
}
}
printf("\n");
}
return 0;
}
It took me a couple of days but i finally got how to do this. Apparently, it was not as complicated as i thought... here is the working code. Thanks to everyone who helped :)
#include <stdio.h>
int main() {
int T, N;
scanf("%d", &T);
for (int i = 0; i<T; i++) {
scanf("%d", &N); getchar();
//INPUT elements and counting frequncy for each element
int f[200001] = {0}, E = 0;
for (int j = 0; j<N; j++) {
scanf("%d", &E); getchar();
f[E]++;
}
//find max frequency and how many elements with max frequency
int max = 0, c = 0;
for (int j = 1; j<200001; j++) {
if (f[j] == max) {
c ++;
}
if (f[j]>max) {
max = f[j];
c = 1;
}
}
//OUTPUT result
printf("Case #%d: %d\n", i+1, max);
int counter = 0;
for (int j = 1; j<200001; j++) {
if (f[j] == max) {
counter ++;
if (counter<c){
printf("%d ", j);
} else {
printf("%d\n", j);
}
}
}
}
return 0;
}

How to print all the prime numbers from 1 to 1000?

I'm trying to write a program that goes through all the numbers from one to a thousand, but it does not work. Here is what I wrote so far, I could not find the problem:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int i = 0, j = 0, mona = 0;
bool prime = true;
//for each number between 1-1000
//i go over the numbers between two(It's ok if the number is divisible by 1,Every number is divisible
by 1) and this number (not including the number itself)
//if the number is divisible by any number, it is not a prime number
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j == 0)
prime = false;
if (prime)
{
printf("prime number: %d\n", i);
mona++;
}
}
}
printf("number of prime numbers: %d", mona);
return 0;
}
and this is the output i got:
prime number: 3
number of prime numbers: 1
I also see that I did not consider the number two.
This can be a solution:
int i, int j;
int count=0;
int mona=0;
for(i = 2; i <= 1000; i++)
{
for (j = 2; j < i; j++) {
if (i % j != 0)
count++;
}
if (count==i-2){
printf("prime number: %d\n", i);
mona++;
}
count=0
}
With "count", you count the number of division with rest different from 0. If all the division satisfy the previous condition, the number is prime. The number of division computed by second cycle for a specific number is equal to i-2.
You want
for(i = 2; i <= 1000; i++)
{
prime = true;
for (j = 2; j < i; j++) {
Clearly if the flag is tested every time around the outer loop it needs to be initialized every time around the outer loop.

Frequency of an Element Accruing In an Array

I am new to programming, I am trying to write a program that lets the user input numbers ranging from 0 to 1000, and the maximum number the user can input is 100. The numbers in the array don't have to be in order, and the program ends when the user inputs a negative number. After that, the program should determine which number occurs the most and the frequency of that occurrence.
I have written a similar code but not for this type of problem the code below showcases what I mean by similar code and any help would be appreciated
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char again;
do {
srand(time(0));
int myNumbers[10];
int i, n, findnum, time, num;
n = 10;
for (i = 0; i < n; i++) {
myNumbers[i] = rand() % 10 + 1;
}
for (i = 0; i < n; i++) {
printf("elements %d\n", myNumbers[i]);
}
printf("Enter number to find Occurrence: ");
scanf("%d", &findnum);
time = 0;
for (i = 0; i < n; i++) {
if (myNumbers[i]==findnum)
time++;
}
if (findnum>0) {
printf("Occurrence of %d is: %d times\n",findnum,time);
} else {
printf("The number %d is not present in the array\n",num);
}
do {
printf("Shall we play again (y/n)?: ");
while(getchar()!='\n');
scanf("%c", &again);
}
while(again !='y' && again !='n');
}
while(again =='y');
}
You will need a second array to count the frequencies. Worst case, the user entered unique numbers, so the second array should be as large as myNumbers. The array will hold two values: the number, and its count:
int myNumbers[10];
int myCount [10][2] = {0};
int n= 10;
You remember the first entry of myCount that is available:
int m= 0;
You cycle over all numbers:
for (i = 0; i < n; i++){
For each number, you check if it is already in the myCount and if yes, increment the count and then exit the loop:
for (j = 0; j < m; j++){
if (myCount[j][0] == myNumbers[i]){
myCount[j][1]++;
break;
}
}
If the number was not found, you add it:
if (j == m) {
myCount[m][0] = myNumbers[i];
myCount[m][1] = 1;
m++;
}
}
Now you can search the array for the number with the highest count.
Integrated the code is:
int myNumbers[10];
int myCount [10][2] = {0};
int n= 10;
int m= 0;
/* now fist read the input */
for (i = 0; i < n; i++){
for (j = 0; j < m; j++){
if (myCount[j][0] == myNumbers[i]){
myCount[j][1]++;
break;
}
}
if (j == m) {
myCount[m][0] = myNumbers[i];
myCount[m][1] = 1;
m++;
}
}
To do: search the array for the number with the highest count.

Printing prime numbers up to n

I have written some code to ask the user for n, then print the prime numbers up to n. However when I use it, i.e with 10, it only prints the non-prime numbers
/* Asks for the amount of prime numbers you would like to print, then prints them */
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
if (check == 1) {
printf("%d\n", i);
}
}
}
}
return 0;
}
How many prime numbers would you like to print? 10
4
6
6
8
8
9
10
10
I've tried everything but I think I am missing something really trivial!
This is how it should be:
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
Also, in the inner loop you don't have to divide the number till j < i. You don't have to go beyond i/2.
As Weather Vane said, the mod operator % returns 0 if i is exactly divisible by j and if this is true then the number is not prime. Your conditional statement is backwards.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
return 0;
}
How many prime numbers would you like to print? 10
2
3
5
7
Several problems.
First, when you set check = 1, that means that i divides evenly, so n is not prime, so you shouldn't print it. You should be printing the number when check == 0.
Second, you're printing each time through the inner loop. You should test check at the end of the loop, to ensure that none of the numbers divided it.
As an improvement, there's no need to keep checking once you find one number that divides evenly. So you can break out of the inner loop as soon as you set check = 1.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
break;
}
}
if (check == 0) {
printf("%d\n", i);
}
}
return 0;
}
try looking at this code
#include <stdio.h>
int IsPrime(int num)
{
int i = 2;
for (i = 2; i < num; i++) if (num % i == 0) return 0;
return 1;
}
int main(void)
{
int n, i;
char *nStr = (char*)malloc(10);
printf("How many prime numbers would you like to print? ");
fgets(nStr, 9, stdin);
n = atoi(nStr);
for (i = 1; i <= n; i++) if (IsPrime(i)) printf("%d\n", i);
getchar();
return 0;
}
and about your code, you should print the number only if check remains 0.

Resources