Printing Out Prime Numbers in C - c

I'm attempting to print out the prime numbers up to a certain value that is obtained from the user. I imagine there is something wrong with my for loop if I only ever receive an answer of 1?
#include <stdio.h>
#include <cs50.h>
int main (void)
{
printf("Length: ");
int length = GetInt();
bool notPrime = false;
for (int i = 1; i < length; i++)
{
for (int k = 1; k <= i/2; k++)
{
if (i % k == 0)
{
notPrime = true;
break;
}
else
{
notPrime = false;
}
}
if (notPrime == false)
{
printf("%d ", i);
}
}
printf("\n");
}

In the internal loop:
for (int k = 1; k <= i/2; k++)
You are starting with k = 1 and testing if k divides i. 1 divides any integer, so the answer will always be "non prime", which is not the case (remember the definition of prime number). Start from 2:
for (int k = 2; k <= i/2; k++)

in the internal loop:
for(k=2; k<=sqrt(i); k++)
will work.

You may have to check the special cases and you can start from 3.
Also you can increment by 2 exluding the pair numbers:
for(int i = 1; i < length; i++){
if(number < 2) prime = true;
if(number == 2) prime = false;
if(number % 2 == 0) prime = false;
for (int k = 3; k <= i/2; k++){
if(number % i == 0 ){
prime = false;
break;
}
}
if (prime){
printf("%d ", i);
}
}
You should make the IF's out of the first bucle, and also you can change k <= i/2 -> sqrt(i)

Related

Printing prime factors of numbers in C

The code fits the first number and prints it constantly. how can i fix this?
int count = 0;
for (int i = 0; i <= 20; i++) {
for (count = 2; i > 1; count++) {
while (i % count == 0) {
printf("%d ", count);
i = i / count;
}
}
}
The values in each iteration are as follows.
count = 0; i = 0; Doesn't enter the second for.
count = 0; i = 1; Doesn't enter the second for.
count = 0; i = 2; Enters the second for. count = 2;
2 % 2 == 0 - Enters the while.
i = 2 / 2; 1 % 2 == 1; Doesn't enter the while.
Back to the second for - count = 3;, i = 1; Doesn't enter the second for.
Back to the first for - i < 20;, so i = 2.
count = 2; i = 2; and we are back to step 4, with an infinite loop.
This might be what you are looking for -
int j, count = 0;
for (int i = 20; i > 0; i--)
{
printf("\n%d: ", i);
for(count = 2, j = i; j > 1; count++)
{
while(j % count == 0)
{
printf("%d ", count);
j = j / count;
}
}
}
Define a function that checks whether a given number n is prime:
bool is_prime(int n)
{
if (n < 2) return false;
for (int i = 2; i <= n/i; ++i) // Doing i*i<=n may overflow
if (n % i == 0) return false;
return true;
}
And then call it like:
for (int i = 0; i <= 20; i++)
if(is_prime(i))
printf("%d\n", i);
Or more directly (i.e. without a function):
int main(void)
{
int mark;
for (int n = 2; n <= 20; n++) {
mark = 1;
for (int i = 2; i*i <= n; ++i)
if (n % i == 0) mark = 0;
if (mark) printf("%d\n", n);
}
}

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.

Random lottery number generator in C programming

I want to do generate 7 different number (0-9) - first digit should not be 0- and put them into an array. Every number should be unique. I know what I did wrong but I dont know what should I do.
int arr[7], j, i;
srand(time(NULL));
for (i = 0; i < 7; i++)
{
arr[i] = rand() % 10;
if (arr[0] == 0)
arr[0] = rand() % 10;
}
for (i = 0; i < 7; i++)
{
for (j = 0; j < 7; j++)
{
if (i == j) {
j++;
}
if (arr[i] == arr[j])
arr[j] = rand() % 10;
}
}
printf("\n");
for(j=0;j<7;j++)
printf("\n%d ", arr[j]);
You can use rand() % 9 + 1 to produce random number between 1 and 9.
arr[j] may be out-of-range after j++;.
Try this:
int arr[7], j, i;
srand(time(NULL));
arr[0] = rand() % 9 + 1; /* decide first number with special formula */
for (i = 1; i < 7; i++) /* decide the rest numbers */
{
int dupe = 0;
arr[i] = rand() % 10;
for (j = 0; j < i; j++) /* check against numbers that already decided */
{
if (arr[i] == arr[j])
dupe = 1; /* ouch, this number is already used! */
}
if (dupe)
i--; /* if the number is already used, try again */
}
printf("\n");
for(j=0;j<7;j++)
printf("\n%d ", arr[j]);

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.

Input sequence contained in an array

I'm trying to implement this excercise but it doesn't work very well. It should tell me if the sequence in array B is contained in A. Any ideas? I have a problem getting it to work for every sequence.
#include <stdio.h>
#include <stdlib.h>
#define N 6
#define M 3
int contains(int v[], int n);
/*
*
*/
int main(int argc, char** argv)
{
int A[N], B[M];
int i, j = 0, flag = 0, contained = 1;
printf("Array A\n");
for (i = 0; i < N; i++)
{
printf("Insert element: ");
scanf("%d", &A[i]);
}
printf("Array B\n");
for (i = 0; i < M; i++)
{
printf("Insert element: ");
scanf("%d", &B[i]);
}
for (i = 0; i < (N - M + 1); i++)
{
flag = 0;
if (A[i] == B[j])
{
flag = 1;
j++;
}
if (flag == 0 && (i == N-M))
{
contained = 0;
printf("The sequence B is not contained in A!\n");
break;
}
}
if (contained == 1)
{
printf("The sequence B is contained in A\n");
}
return (EXIT_SUCCESS);
}
When you have a non match in the sequence, you never reset j so you start looking for the rest of the sequence starting to what ever value j was left at. Your program looks for the sequence B but doesn't require it to be contiguous.
You also don't check for when the sequence is completed so it for example B is at the start of A the j will keep incrementing and B[j] will overflow into unknown memory which is unlikely to match A so will give you an incorrect result. To fix this just check for when the whole of B is found and exit the loop.
Substituting the following will fix this:
if (j == M) break; // Break the loop when B sequence is found
if (flag == 0)
{
j = 0; // This was missing
if (i == N-M)
{
contained = 0;
printf("The sequence B is not contained in A!\n");
break;
}
}
For the third for loop when you're doing the check, you're (1) not actually checking every element of B against the corresponding element of A and (2) not checking the different start indices. What you probably meant to do is something like
for (i = 0; i < (N - M + 1); i++) {
for (j = 0; j < M; j++) {
if (A[i + j] != B[j]) {
break;
}
}
if (j == M) {
printf("Found a match!");
}
}
as your spinning through A if you find that an element of B does not match A then you need to set j back to 0
for (i = 0; i < (N - M + 1); i++)
{
int j;
for(j = 0; j < M; j++)
{
if(B[j] != A[j + i])
break;
}
/* sequence found */
if(j == M)
{
return true;
}
}
return false;
For searching B in A you may want to do something like following:
for (i = 0; i < (N - M + 1) ; i++)
if (A[i] == B[0])
{ j=0;
while (A[++i] == B[++j] && j<M);
break;
}
if (j == M)
{
printf("The sequence B is contained in A\n");
}
else{
printf("The sequence B is not contained in A\n");
}
GCC has the memmem() extention function (which is basically strstr(), but does not rely on NUL-terminated strings)
if (memmem(A, N * sizeof *A, B, M * sizeof *B)) {
printf("Found\n" );
} else {
printf("Not Found\n" );
}

Resources