Search function

Joined
Nov 2, 2024
Messages
1
Reaction score
0
can anyone help me with my code? i don't know why it keeps on printing -1.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define SIEVE_MAX 1000000

int sieve[SIEVE_MAX];

void sieve_eratostene(){
sieve[0] = sieve[1] = 1;

for(int i=2 ; i<=SIEVE_MAX ; i++)
if(sieve==0)
for(int j=2 ; j*i<=sieve_MAX ; j++)
sieve[i*j] = 1;
}


int through_search(int* vector, int searched_element, int number_of_intervals, int interval_length, int* left) {
for (int start = (*left); start < interval_length * number_of_intervals; start += interval_length) {
if (vector[start] == searched_element)
return start;
else if (vector[start] > searched_element && searched_element < vector[start + interval_length]) {
(*left) = start;
return 1;
}
}
return -1;
}

int search(int* vector, int size_vector, int searched_element){
int divizor = 0, result = 1;
int left = 0;
while(size_vector!=1 && result == 1){
if(sieve[divizor]==0)
while(size_vector != 1 && size_vector%divizor==0 && result == 1){
size_vector /= divizor;
result = through_search(vector, searched_element, divizor, size_vector, &left);
}
divizor++;
}
return result;
}

int main(){
int vector[] = {1, 3, 6, 9, 10, 15, 16, 19, 23, 27, 31, 45, 67, 88};
int size_vector = sizeof(vector)/sizeof(vector[0]);
sieve_eratostene();
int searched_element;
scanf("%d", &searched_element);
printf("%d\n", search(vector, size_vector, searched_element));
return 0;
}
 
Joined
Sep 20, 2022
Messages
230
Reaction score
38
Can you explain what the program should be searching for?

There are no comments.

I need to see the expected output, or a comment.

At the moment, the only obvious problem is the sieve. Thats not the best way to do it.
 
Joined
Sep 20, 2022
Messages
230
Reaction score
38
The main bug is in the through_search function.
Code:
vector[start] > searched_element
> should be <

Your naming is misleading.

For anyone else reading this thread, its like a binary search, but is using prime numbers instead of 2.
 
Joined
Sep 20, 2022
Messages
230
Reaction score
38
On second thoughts, its a jump search. There is a wikipedia article about it.

Have you considered computing the primes as you go, instead of precomputing with a sieve?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,260
Messages
2,571,038
Members
48,768
Latest member
first4landlord

Latest Threads

Top