Finding prime numbers with Sieve of Eratosthenes algorithm in c - c

I am trying to find the first 1000 prime numbers using an algorithm called "Sieve of Eratosthenes"
Basically, you have a list of ascending numbers 2,3,4 ... and this list represents potential prime numbers; Number 2 is prime so it is printed, then, we check the list for any multiples of 2. If we find any, we omit them. And keep going till we have our correct list.
I thought of using nested loops for this one, and although I don't feel like it's a perfect idea; I don't see why it won't work. Here is my code. It doesn't run at all
#include <stdio.h>
#include <stdlib.h>
int main()
{
int primelist[999];
int n = 2;
for (int i = 1; i <= 999; i++)
{
primelist[i] = i;
}
for (int i = 0; i <= 999; i++, n++)
{
while (primelist[i] != 0) {
for (int i = 0; i <= 999; i++)
{
if ( (primelist[n] % primelist[i]) == 0 )
{
primelist[i] = 0;
}
}
}
}
}

Related

How to sort a 2d array based on these conditions ? (The conditions are given within the code)

/*
The program must accept N integers as the input. Each integer is
given a weight. The program must sort the integers in ascending
order based on their weight and print the integers along with their
weights as the output as given in the Example Input/Output
sections. The weight of each integer is calculated based on the
conditions given below.
Conditions:
Weight = 5 if it is a perfect cube.
Weight = 4 if it is a multiple of 4 and divisible by 6.
Weight = 3 if it is a prime number.
Hint: Use stable sort (insertion sort, bubble sort or merge sort).
Boundary Conditions:
1 <= N <= 1000
Input Format:
The first line contains N.
The second line contains N integers separated by a space.
Output Format:
The first line contains integers with their weight as given in the Example Input/Output sections.
Example Input/Output 1:
Input:
7
10 36 54 89 12 216 27
Output:
<10,0>,<54,0>,<89,3>,<36,4>,<12,4>,<27,5>,<216,9>
Example Input/Output 2:
Input:
10
12 18 16 64 14 30 37 27 343 216
Output:
<18,0>,<16,0>,<14,0>,<30,0>,<37,3>,<12,4>,<64,5>,<27,5>,<343,5>,<216,9>
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int perfcube(int n)
{
int cubert = cbrt(n);
if (cubert * cubert * cubert == n)
{
return 1;
}
else
return 0;
}
int divis(int n)
{
if (n % 4 == 0 && n % 6 == 0)
{
return 1;
}
return 0;
}
int prime(int n)
{
int count = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
count++;
}
}
if (count == 2)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int n;
scanf("%d", &n);
int a[n];
int b[n][2];
// scanning n variables into array a
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// copying rows of a(1d array) to b(2d array)
int l = 0; // variable to traverse 1d array without its own loop
// traverse 2d array
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 2; k++)
{
if (k == 0)
{
// if k = 0 that is first col then store 1st col value of 1d array to 2d array
b[j][k] = a[l++];
}
else
{
// if other cols come then skip it
continue;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
if (j == 0)
{
if (perfcube(b[i][j]))
{
b[i][j + 1] += 5;
}
if (divis(b[i][j]))
{
b[i][j + 1] += 4;
}
if (prime(b[i][j]))
{
b[i][j + 1] += 3;
}
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
printf("<%d,>", b[i][j]);
}
printf("\n");
}
return (0);
}
I tried approaching the problem like this and ended up with an output like this. Please help me proceed from here.
Output
<10,><0,>
<36,><4,>
<54,><0,>
<89,><3,>
<12,><4,>
<216,><9,>
<27,><5,>
I am new to programming
I have tried approaching the problem like this and ended up with an output like that.
Please help me proceed from here.
I am not allowed to use pointers or functions like qsort
How do I sort these in that format and print it
Output of the program that I ended up with.
The output should match the question.
Sorting, at its core, centers around the comparison of two items. For example, if A < B, then A should come before B.
For example, we can reorder
3 5 2 1 4
to
1 2 3 4 5
We can see it is correct because each adjacent pair maintains a ≤ relationship.
This relationship is a comparison function. The one used for your standard sorting looks something like this:
bool compare( int a, int b )
{
return a <= b;
}
 
What your homework is asking you to do is change the comparison function to not compare the values directly, but compare the results of a function applied to them:
bool compare( int a, int b )
{
return weight_function( a ) <= weight_function( b );
}
You must write and implement the weight function, then use it in your sorting algorithm.
(Your algorithm probably has an if (a <= b) in it somewhere, which you could rewrite as if (compare( a, b ))... but you don’t need to do that, just use the weight functions properly.

Calculating primes using wiki algorithm

I have just started using C and I am currently working on calculating primes using the wikipedia algorithm here:
algorithm Sieve of Eratosthenes is
input: an integer n > 1.
output: all prime numbers from 2 through n.
let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n do
if A[i] is true
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
A[j] := false
return all i such that A[i] is true.
When I try implementing what I think turns out like the code above, I get what I believe is an 'infinite loop', where might I have gone wrong?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//create empty array to store values
int isPrime[] = {};
//set a large number
int n = 1000;
//create for loop
for(int i = 2; i < n; i++){
///create another for loop taking the exponents
for(int j = i; j < pow(i, 2); j++){
//if i is equal to j is true then return those values true
if(isPrime[i] == isPrime[j]){
printf("%d", isPrime[i]);
}
}
}
There's many errors in your code including an empty array, use of pow (which is a floating-point function) and numerous logic errors that deviate from the wikipedia example code.
Here's a corrected, working version that follows the logic of the wikipedia version, with a loop afterwards to print out all the primes less than n:
#include <stdio.h>
int main(void) {
int n = 1000;
int isPrime[n];
for (int i = 0; i < n; i++) {
isPrime[i] = 1;
}
for (int i = 2; i * i < n; i++) {
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = 0;
}
}
}
for (int i = 2; i < n; i++) {
if (isPrime[i]) {
printf("%d ", i);
}
}
printf("\n");
}
(Note that a small deviation from the wikipedia algorithm is that this prints primes less than n rather than primes less than or equal to n).

Replacing all duplicate numbers in an Array, so that every element is unique in C

The elements in the array are created using rand().
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void){
int array[6] = { 0 };
srand(time(NULL));
for(int i = 0; i < 6; i++){
array[i] = rand() % 49 + 1;
}
/*
Code to check for duplicates
if duplicate found
duplicate = rand(49);
*/
for(int i = 0; i<6; i++){
printf("[%d]",array[i]);
}
return 0;
}
I don´t really want to sort the array if it makes it easier to find duplicates because the array is for a lottery ticket.
I have tried different methods, but all of them are inefficient and includes a lot of loops.
I had different approaches, but all of them didn´t really work, because what if, the newly created number, is yet again a duplicate? Or if the last number in the array is a duplicate.
So I came with the following approach: The algorithm will create as many areas, as long no number in the array is a duplicate
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define TRUE 1
int main(void) {
int a[6] = {0};
srand(time(NULL));
while (TRUE) {
int c = 0;
for (int i = 0; i < 6; i++) {
a[i] = rand() % 49 + 1;
}
for (int i = 0; i < 6; i++) {
for (int j = i + 1; j < 6; j++) {
if (a[i] == a[j]) {
c++;
}
}
}
if (c == 0) {
break;
}
}
for (int i = 0; i < 6; i++) {
printf("%d\n", a[i]);
}
return 0;
}
Any Ideas, how to make an easy, efficient, but not so complex algorithm for a beginner?
Thanks :)
There's two sort of problems here. Firstly, if you find a duplicate number, you wish it to be replaced by another number. However, it is also possible that the new number could be a duplicate to some other value. I'd suggest adding the following code to your program to check for duplicacy
for(int i = 0; i<6; i++)
{
for(int k=0; k<6; k++)
{
if(i==k)
{
continue;
}
if(array[i] == array[k])
{
array[i]=rand()%49+1;
}
}
}
There is an outer loop to rotate between the 6 elements of the array, and an inner loop to test that element against all other elements of that array. However, you should note that it is entirely possible that the elements 1-5 may end up being duplicated to some other value again.
Edit: The continue; statement iterates the loop for the next value. Its there to make sure no element is tested against itself.

Problem with C program to find Sudoko square 3x3 if exist in Matrix RXC

#include <stdio.h>
#include <stdlib.h>
#define R 4
#define C 5
// functions for option 1 initializeCountArray and TestCount and Sudoku
void initializeCountArray(int *count)
{
int i;
for (i = 0; i < 10; i++)
count[i] = 0;
}
int TestCount(int *count)
{
int i;
for (i = 1; i < 10; i++)
if ( count[i] == 1)
count[0]++;
return 1;
}
int Sudoku(int mat[R][C])
{
int count[10] = { 0 };
int rows,cols,i,j;
for(rows=0; rows<R-2; rows++)
{
for (cols = 0; cols<C-2; cols++)
{
initializeCountArray(count);
for (i = rows; i <= rows+2; i++)
{
for (j = cols; j <= cols+2; j++)
{
count[ mat[i][j] ] ++;
printf("\n%d,%d",i,j);
}
}
printf("\n TestCount=%d",TestCount(count));
if (TestCount(count) == 9)
return 1;
}
}
return 0;
}
void main ()
{
int mat[R][C] = {{1,7,8,9,6},
{1,3,3,4,6},
{1,1,1,2,5},
{1,6,7,8,9}};
printf ("\n Check Matrix if Suduku 3X3 square found");
if (Sudoku(mat) == 1)
printf("\n Sudoku square matrix was found\n");
else
printf("\n Sudoku square matrix NOT found\n");
}
This program should solve a specific code test that we got in class with the functions that included
and we can not use other methods when running the program the TestCount function give wrong number as output I used test printouts of indexes and I can not figure what is wrong please help
First of all:
In your TestCount function you use your count[0] as a counter for the numbers that appear in the 3x3 submatrix. I guess you wanted to do:
return count[0];
instead of your:
return 1;
Second, you do this:
printf("\n TestCount=%d", TestCount(count));
if (TestCount(count) == 9)
return 1;
But notice your TestCount has some side effects. First time you call it, count[0] would get 9 for a Sudoku-styled 3x3 matrix, but the second time you continue incrementing count[0], so it would get 18 and fail the == 9 check - Eventually your Sudoku function misses it.
You should probably either set count[0] = 0; between calls of TestCount(), reset count[0] to 0 before you start counting in TestCount() or anything else you could think of (just make sure you don't overwrite it).

c programming - printing sequence of sum of squared digits (as an array) for a potential happy number

I have this assignment for my intro to C programming class and part of my code has to find the sequence of the sum of square digits of a number in order to determine after if the given number is a happy number (sum of square digits = 1)
Here's part of my code:
#include <stdio.h>
#include <math.h>
// The sum of square digits function
int sqd (int x) {
int sum = 0;
while (x > 0) {
sum = sum + pow(x%10, 2);
x = x/10;
}
return sum;
}
// The search function
int search (int a[], int val, int size) {
int i;
for (i = 0; i < size; i++) {
if (a[i] == val) {
return 1;
}
}
return 0;
}
// The main program
void main () {
int a [1000] = {0};
int N;
int count = 1;
int j;
printf("Please enter the potential happy number:\n", N);
scanf ("%d", &N);
a[0] = N;
a[count] = sqd (N);
do {
a[count] = sqd (a[count-1]);
count++;
} while (search (a, a[count], count));
for ( j = 0; j <= count; j++) {
printf("%d\n", a[j]);
}
}
It only prints the first three sums in the sequence. I really don't know how to make it work.
Thank you in advance
This line
while (search (a, a[count], count));
makes sure that you break out of the loop after one round since a[1] is not equal toa[0]. You can change that line to be:
while (a[count-1] != 1);
You also need to add a clause to make sure that you stop when the limit of the array is reached. Update that line to be:
while (a[count-1] != 1 && count < 1000 );
And then, change the printing loop to use i < count, not i <= count. Using <= will result in accessing the array out of bounds when the user enters a sad number.
for ( j = 0; j < count; j++){
printf("%d\n", a[j]);
}
Update
After a bit of reading on happy numbers at Wikipedia, I understand why you had call to search in the conditional of the while. The following also works.
} while ( ! (a[count-1] == 1 || search(a, a[count-1], count-1)) );
That will search for the last number in the array but only up to the previous index.

Resources