Printing prime numbers up to n - c

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.

Related

Block values that are smaller than the previous iteration

This loop checks the previous element in an array. The question is how can it be avoided to check the arr[0][0] with its previous element which causes undefined behavior?
Here is the code so far but it has this issue with the the first element being checked with its previous element.
int main()
{
int arr[2][4];
int k, n;
for (k = 0; k < 2; k++) {
for (n = 0; n < 4; n++) {
do {
printf("Provide a number");
scanf("%d", &arr[k][n]);
printf("This is %d in the position[%d][%d]\n", arr[k][n], k, n);
if (n==0) break;
printf("The arr[k][n] is %d and the arr[k][n-1] is %d and n-1 means %d\n", arr[k][n], arr[k][n - 1], n - 1);
} while (arr[k][n] <= arr[k][n - 1]); //Here is the issue
}
}
for (k = 0; k < 2; k++) {
for (n = 0; n < 4; n++) {
printf("%d\n", arr[k][n]);
}
}
}
The issue:
Adding the if (n==0) break; causes the program to allow adding smaller numbers than the ones inserted so far. While not including this line causes undefined behavior. How can this be fixed?
This is how it works now, which is not correct:
2 3 4 5
2 4 5 6
The printf statements are only for the purpose of viewing what is going on.
You only check with previous column. That is not related to your break but due to broken logic.
You could do it like this:
int main()
{
int arr[2][4];
int k, n;
int last_number, new_number;
for (k = 0; k < 2; k++) {
for (n = 0; n < 4; n++) {
do {
printf("Provide a number");
scanf("%d", &new_number);
printf("This is %d in the position[%d][%d]\n", new_number, k, n);
if (n==0 && k == 0)
break; // Don't check for increasing values.
} while (new_number < last_number);
arr[k][n] = new_number;
last_number = new_number;
}
}
for (k = 0; k < 2; k++) {
for (n = 0; n < 4; n++) {
printf("%d\n", arr[k][n]);
}
}
}
Change
while (arr[k][n] <= arr[k][n - 1]);
to
while (n > 0 && arr[k][n] <= arr[k][n - 1]);
This works because && short circuits the test when n == 0 and does not do the second test.
You will also need to fix the print statement.

Problem with program to list primes below integer using arrays and nested loops

#include <stdio.h>
#include <math.h>
#define MAX_SIZE 10000
int main(void)
{
int a[MAX_SIZE];
int N;
int L; /* the current size of the list */
/* read in the upper limit. Keep reading until
a valid number between 3 and the maximum that
can be handled by the array is entered */
double b[10000];
int j, i;
L = 0;
printf("Enter the upper limit:\n");
do {
scanf("%d", &N);
} while (N<3 || N>MAX_SIZE+2);
int prime;
for (j = 1; j < N; j++)
{
prime = 1;
for (i = 2; i < j; i++)
{
if (j % i == 0)
{
prime = 0;
break;
}
}
if (prime)
{
a[i] = j;
L++;
}
}
/* write out the result - DO NOT CHANGE THIS */
for(i=0;i<L;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
Program needs to take an integer, calculate primes below that integer, print that list of primes.
I think my problem is related to the loops.
The program is calculating the primes but listing 0 if the number previously there isnt prime eg a[4] is now printing as 0
Any help is appreciated.
thanks.
Is this what you were trying to implement?
#include <stdio.h>
#define MAX_SIZE 100
int main(void)
{
int primes[MAX_SIZE];
int primes_found = 0;
int limit = 0;
while (limit < 3)
{
printf("Enter the upper limit:\n");
scanf("%d", &limit);
}
for (int candidate = 2; candidate <= limit && primes_found < MAX_SIZE; candidate++)
{
int divisor = 2;
int is_prime = 1;
while(is_prime && divisor < candidate)
is_prime = candidate % divisor++ != 0;
if (is_prime)
primes[primes_found++] = candidate;
}
for (int i = 0 ; i < primes_found ; i++)
printf("%d ", primes[i]);
printf("\n");
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.

C - Next 10 prime numbers

I'm having some problems with a program I'm writing here.
It's supposed to print the next 10 prime numbers of given a value -- of course, it's not working. My logic is at fault here.
For example, if the program reads the number:
2
it's supposed to print:
3, 5, 7, 11, 13, 17, 19, 23, 29, 31
Code:
#include <stdio.h>
int main() {
int n, i, count, primenumber = 1; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
for (count = 0, n++; count < 10; n++, count++ ) {
for (i = 2; i < n; i++) {
if (n % i == 0) {
primenumber = 0;
break;
}
}
if (primenumber)
printf("%d\n", n);
}
return 0;
}
I'd be very grateful if someone were to solve this problem.
Thanks.
==UPDATE==
I did it!
The crucial change was with the primenumber flag. I inserted it inside the while, always set to 1. If set outside the while, the flag never resets and further tests won't occur -- depending on the number you give when prompted.
Here's the updated, functional code:
#include <stdio.h>
int main() {
int n, i, count = 0, primenumber;
printf("Insert a number: ");
scanf("%d", &n);
n++; // we do not want to print the prompted number
while (count < 10) {
primenumber = 1; // primenumber is set as flag
for (i = 2; i < n / 2; i++) {
if (n % i == 0) {
primenumber = 0;
break;
}
}
if (primenumber) {
printf("%d\n", n);
count++; // increment count only when prime
}
n++;
}
return 0;
}
I decided not to delete this post. I'm sure someone, someday, will find it useful.
Split your code a little arrange a bit more and present it
int isPrime ( int n )
{
if (n <= 1) return 0; // zero and one are not prime
unsigned int i;
for (i=2; i*i<=n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
int main() {
int n, count; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
count = 0 ;
n++ ;
for ( ; count < 10; n++ ) {
if (isPrime(n)) { // if its Prime, print and increase count
printf("%d\n", n);
count ++;
}
// Check next number until we get all our numbers
}
return 0; // All Done
}
This is your modified working code.
In each step you should re initializing primenumber=1 otherwise it gives only one number. Also count should be increases when you find a prime otherwise not.
#include <stdio.h>
int main() {
int n, i, count, primenumber = 1; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
for (count = 0, n++; count < 10; n++ ) {
primenumber = 1;
for (i = 2; i < n; i++) {
if (n % i == 0) {
primenumber = 0;
break;
}
}
if (primenumber){
count++;
printf("%d\n", n);
}
}
return 0;
}
Here is a solution which will reduce the processing time, generally used for larger values of n:
#include <stdio.h>
#include <math.h>
int main() {
int n, i, count= 1, primenumber = 1, root; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
n++;
while(count!=11)
{
root= sqrt(n);//You only need to check for range 2 to square root of number. This is the key ingredient of the code to reduce time complexity
primenumber = 1;
for(i=2; i<= root; i++)
{
if(n%i==0)//As soon as it finds a number which perfectly divides it, break from loop checking n's nature
{
primenumber = 0;
break;
}
}
if(primenumber==1)
{
printf("%d \t", n);
count++;
}
n++;
}
}

Resources