This is the given condition and I have problem with setting time interval
Find prime numbers from 2 in 5 minutes:
include <time.h>
end= start = (unsigned)time(NULL);
while((end-start)<300)
find primes
print the prime number and how many primes are there(frequency)
end = (unsigned)time(NULL);
print total execution time
And this is the code I did.
#include <stdio.h>
#include <time.h>
int main()
{
time_t end, start;
end = start = (unsigned)time(NULL);
int i, j;
int freq = 0;
int count = 0;
while ((end-start) < 300) {
for (i = 2;; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
count = 1;
break;
}
}
if (!count) {
++freq;
}
count = 0;
}
return i, freq;
printf("Prime number: %d, frequency: %d\n", i, freq);
}
end = (unsigned)time(NULL);
printf("total time : %d seconds\n", end);
return 0;
}
I checked the finding prime part and the frequency part was fine when I put this way`
}
count = 0;
printf("Prime number: %d, frequency: %d\n", i, freq);
}
return i, freq;`
but there's no result even after the 5 minutes
Your while cycle ends when according to the value of end
and start
5 minutes passed. They are initialized with the same value.
end
is never updated inside the loop, so this will be an infinite cycle. You update end
after the loop, but that is too late. You need to update it at each step, like:
while ((end-start) < 300) {
for (i = 2;(end-start) < 300; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
count = 1;
break;
}
}
if (!count) {
++freq;
}
count = 0;
end = (unsigned)time(NULL); printf("Prime number: %d, frequency: %d\n", i, freq);
}
//Don't return at this point
//return i, freq;
}