Why is my pthread program missing prime numbers? - c

I am working on a program that utilizes pthreads in C. The function of the thread is to compute prime numbers based on a maximum number entered by the user at the CLI. Thus say for instance, the user enters ./ComputePrimes 20, the output should be 2, 3, 5, 7, 11, 13, 17, 19.
However, for some reason, my program only outputs 2 to 13 (thus my output is 2, 3, 5, 7, 11, 13).
I am using a formula based off of Wilson's Theorem for computing primes:
https://en.wikipedia.org/wiki/Formula_for_primes
I know from a Discrete Mathematics class I have taken in the past that there is no solid formula for computing primes. The purpose of this program however is to demonstrate pthreads which I believe I have done successfully. Here is my program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *generatePrimeNumbers(void *primenum) {
int i, j, a, b;
int primeNumbers[] = {};
int limit = (int *)primenum;
for (i = 1; i <= limit; i++) {
j = 0;
int a = (factorial(i) % (i + 1));
int b = (i - 1) + 2;
if (((a / i) * b) != 0) {
primeNumbers[j] = ((a / i) * b);
printf("%d ", primeNumbers[j]);
j++;
}
}
printf("\n");
return NULL;
}
int factorial(int n) {
if (n == 1) {
return 1;
} else return n * factorial(n - 1);
}
int main(int argc, char *argv[]) {
int numLimit;
pthread_t primethread;
if (argc != 2) {
printf("You need to enter a valid number!\n");
exit(-1);
}
else {
int i = 0;
numLimit = atoi(argv[1]);
if (numLimit < 2) {
printf("Please enter a number greater than or equal to 2.\n");
exit(-1);
}
}
pthread_create(&primethread, NULL, generatePrimeNumbers, (void *)numLimit);
pthread_exit(NULL);
}
As you can see below, I successfully create a thread, however some of the prime numbers are missing. I believe that I might have messed up somewhere in my called threads function. Thanks!

In many environment, int can only store integers only upto 2147483647 (2**31 - 1) while 20! = 2432902008176640000. Therefore, factorial(20) cannot be calculated correctly.
Making the return type of factorial to long long will make the output for input 20 correct (supposing that long long can save upto 2**63 - 1), but for larger number, you should consider other method such as taking modulo inside factorial method before the number gets too big.
Also note that the line
int limit = (int *)primenum;
looks weird. The cast should be int, not int *.
Another point is that you are assigning numbers to 0-element array as Retired Ninja said.
In this code, primeNumbers isn't used other than the printing point, so the printing should be done directly like
printf("%d ", ((a / i) * b));

Related

Problem with continue instruction after rand() function

I just wanted to solve an exercise that asks me to write a routine to generate a set of even random numbers between 2 to 10.
The problem is when printing, because I want the last number not to be followed by a comma.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, a, b, c;
i = a = b = c = 0;
srand(time(NULL));
for (i = 2; i <= 10; i++)
{
a = rand() % 8 + 2;
if ((i <= 10) && (a % 2) != 0)
{
continue;
}
printf((i < 10) ? "%d, " : "%d\n", a);
}
return 0;
}
And these are two execution examples:
4, 4, 2, 8,
2, 8, 6, 4, 2
In one the comma does not appear at the end but in another it does. When debugging I see that the error happens when the last number is odd, because the continue statement causes it to go to the next iteration.
As Retired Ninja has said, there are many unnecessary conditionals that can be avoided. I have revised your code so that a will always generate an even number between 2 and 10, thereby removing the need for the logic you implemented. This is what I have assigned this new a value as:
a = ((rand() % 4) * 2 + 2);
This generates a random value between [0,4], multiplies it by 2, and adds 2, for an integer between 2 and 10, noninclusive. Since your new a is always even, I removed your logic to check whether the number is even.
Revised code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, a, b, c;
i = a = b = c = 0;
srand(time(NULL));
for (i = 2; i <= 10; i++)
{
a = ((rand() % 4) * 2 + 2);
printf((i < 10) ? "%d, " : "%d\n", a);
}
return 0;
}
Note that this code will always produce 9 numbers, as you have not specified how many values to print each time, just that you need to "write a routine to generate a set of even random numbers between 2 to 10". You can always change the amount of numbers printed by changing the value of i in the for loop. The comma issue, however, is not a problem anymore.
If my solution has helped you, please mark my answer as the correct answer :)

Finding numbers with unique digits in C

I have to write a program that finds every number (except 0) which can be factored by numbers from 2-9.
For example first such a number would be number 2520 as it can be divided by every single number from 2 to 9.
It also has to be a number that contains only 1 type of digit of its own (no multiple digits in a number). So for example 2520 will not meet this requirement since there are two same digits (2). The example of a number that meets both requirements is number 7560. That is the point I don't how to do it. I was thinking about converting value in an array to string, and then putting this string in another array so every digit would be represented by one array entry.
#include <stdio.h>
#include <math.h>
int main() {
int i, n, x, flag, y = 0;
scanf("%d", &n);
double z = pow(10, n) - 1;
int array[(int)z];
for (i = 0; i <= z; i++) {
flag = 0;
array[i] = i;
if (i > 0) {
for (x = 2; x <= 9; x++) {
if (array[i] % x != 0) {
flag = 1;
}
}
if (flag == 0) {
y = 1;
printf("%d\n", array[i]);
}
}
}
if (y == 0) {
printf("not exist");
}
return 0;
}
This should give you a base:
#include <stdio.h>
#include <string.h>
int main()
{
char snumber[20];
int number = 11235;
printf("Number = %d\n\n", number);
sprintf(snumber, "%d", number);
int histogram[10] = { 0 };
int len = strlen(snumber);
for (int i = 0; i < len; i++)
{
histogram[snumber[i] - '0']++;
}
for (int i = 0; i < 10; i++)
{
if (histogram[i] != 0)
printf("%d occurs %d times\n", i, histogram[i]);
}
}
Output:
Number = 11235
1 occurs 2 times
2 occurs 1 times
3 occurs 1 times
5 occurs 1 times
That code is a mess. Let's bin it.
Theorem: Any number that divides all numbers in the range 2 to 9 is a
multiple of 2520.
Therefore your algorithm takes the form
for (long i = 2520; i <= 9876543210 /*Beyond this there must be a duplicate*/; i += 2520){
// ToDo - reject if `i` contains one or more of the same digit.
}
For the ToDo part, see How to write a code to detect duplicate digits of any given number in C++?. Granted, it's C++, but the accepted answer ports verbatim.
If i understand correctly, your problem is that you need to identify whether a number is consisted of multiple digits.
Following your proposed approach, to convert the number into a string and use an array to represent digits, i can suggest the following solution for a function that implements it. The main function is used to test the has_repeated_digits function. It just shows a way to do it.
You can alter it and use it in your code.
#include <stdio.h>
#define MAX_DIGITS_IN_NUM 20
//returns 1 when there are repeated digits, 0 otherwise
int has_repeated_digits(int num){
// in array, array[0] represents how many times the '0' is found
// array[1], how many times '1' is found etc...
int array[10] = {0,0,0,0,0,0,0,0,0,0};
char num_string[MAX_DIGITS_IN_NUM];
//converts the number to string and stores it in num_string
sprintf(num_string, "%d", num);
int i = 0;
while (num_string[i] != '\0'){
//if a digit is found more than one time, return 1.
if (++array[num_string[i] - '0'] >= 2){
return 1; //found repeated digit
}
i++;
}
return 0; //no repeated digits found
}
// test tha function
int main()
{
int x=0;
while (scanf("%d", &x) != EOF){
if (has_repeated_digits(x))
printf("repeated digits found!\n");
else
printf("no repeated digits\n");
}
return 0;
}
You can simplify your problem from these remarks:
the least common multiple of 2, 3, 4, 5, 6, 7, 8 and 9 is 2520.
numbers larger than 9876543210 must have at least twice the same digit in their base 10 representation.
checking for duplicate digits can be done by counting the remainders of successive divisions by 10.
A simple approach is therefore to enumerate multiples of 2520 up to 9876543210 and select the numbers that have no duplicate digits.
Type unsigned long long is guaranteed to be large enough to represent all values to enumerate, but neither int nor long are.
Here is the code:
#include <stdio.h>
int main(void) {
unsigned long long i, n;
for (n = 2520; n <= 9876543210; n += 2520) {
int digits[10] = { 0 };
for (i = n; i != 0; i /= 10) {
if (digits[i % 10]++)
break;
}
if (i == 0)
printf("%llu\n", n);
}
return 0;
}
This program produces 13818 numbers in 0.076 seconds. The first one is 7560 and the last one is 9876351240.
The number 0 technically does match your constraints: it is evenly divisible by all non zero integers and it has no duplicate digits. But you excluded it explicitly.

prime factorization of factorial in C

I'm trying to write a program that will print the factorial of a given number in the form:
10!=2^8 * 3^4 * 5^2 * 7
To make it quick lets say the given number is 10 and we have the prime numbers beforehand. I don't want to calculate the factorial first. Because if the given number is larger, it will eventually go beyond the the range for int type. So the algorithm i follow is:
First compute two’s power. There are five numbers between one and ten that two divides into. These numbers are given 2*1, 2*2, …, 2*5. Further, two also divides two numbers in the set {1,2,3,4,5}. These numbers are 2*1 and 2*2. Continuing in this pattern, there is one number between one and two that two divides into. Then a=5+2+1=8.
Now look at finding three’s power. There are three numbers from one to ten that three divides into, and then one number between one and three that three divides into. Thus b=3+1=4. In a similar fashion c=2. Then the set R={8,4,2,1}. The final answer is:
10!=2^8*3^4*5^2*7
So what i wrote is:
#include <stdio.h>
main()
{
int i, n, count;
int ara[]={2, 3, 5, 7};
for(i=0; i<4; i++)
{
count=0;
for(n=10; n>0; n--)
{
while(n%ara[i]==0)
{
count++;
n=n/ara[i];
}
}
printf("(%d^%d)" , ara[i], count);
}
return 0;
}
and the output is (2^3) (3^2) (5^1) (7^1).
I can't understand what's wrong with my code. Can anyone help me, please?
Much simpler approach:
#include <stdio.h>
int main(int argc, char const *argv[])
{
const int n = 10;
const int primes[] = {2,3,5,7};
for(int i = 0; i < 4; i++){
int cur = primes[i];
int total = 0;
while(cur <= n){
total += (n/cur);
cur = cur*primes[i];
}
printf("(%d^%d)\n", primes[i], total);
}
return 0;
}
Your code divides n when it is divisible for some prime number, making the n jumps.
e.g. when n = 10 and i = 0, you get into while loop, n is divisible by 2 (arr[0]), resulting in n = 5. So you skipped n = [9..5)
What you should do is you should use temp when dividing, as follows:
#include <stdio.h>
main()
{
int i, n, count;
int ara[]={2, 3, 5, 7};
for(i=0; i<4; i++)
{
count=0;
for(n=10; n>0; n--)
{
int temp = n;
while(temp%ara[i]==0)
{
count++;
temp=temp/ara[i];
}
}
printf("(%d^%d)" , ara[i], count);
}
return 0;
}
For finding factorial of a no pl. try this code:
#include <stdio.h>
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}

C program which is finding "happy" nums recursively

Hello guys i am trying to implement a program which is finding the happy numbers were between two numbers A and B.
Summing the squares of all the digits of the number, we replace the number with the outcome, and repeat the process. If after some steps the result is equal to 1 (and stay there), then we say that the number N is **<happy>**. Conversely, if the process is repeated indefinitely without ever showing the number 1, then we say that the number N is **<sad>**.
For example, the number 7 is happy because the procedure described above leads to the following steps: 7, 49, 97, 130, 10, 1, 1, 1 ... Conversely, the number 42 is sad because the process leads to a infinite sequence 42, 20, 4, 16, 37, 58, 89, 145, 42, 20, 4, 16, 37 ...
I try this right down but i am getting either segm faults or no results.
Thanks in advance.
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void happy( char * A, int n);
int numPlaces (long n);
int main(void)
{
long A,B;
int npA;
char *Ap;
printf("Give 2 Numbers\n");
scanf("%li %li",&A,&B);
npA = numPlaces(A);
Ap = malloc(npA);
printf("%ld %d\n",A,npA);
//Search for happy numbers from A to B
do{
sprintf(Ap, "%ld", A);
happy(Ap,npA);
A++;
if ( npA < numPlaces(A) )
{
npA++;
Ap = realloc(Ap, npA);
}
}while( A <= B);
}
//Finds happy numbers
void happy( char * A, int n)
{
//Basic Condition
if ( n == 1)
{
if (A[0] == 1 || A[0] == 7)
printf("%c\n",A[0]);
printf("%s\n",A);
return;
}
long sum = 0 ;
char * sumA;
int nsum;
int Ai;
//Sum the squares of the current number
for(int i = 0 ; i < n;i++)
{
Ai = atoi(&A[i]);
sum = sum + (Ai*Ai);
}
nsum = numPlaces (sum);
sumA = malloc(nsum);
sprintf(sumA, "%li", sum);
happy(sumA,nsum);
free(sumA);
}
//Count digits of a number
int numPlaces (long n)
{
if (n < 0) return 0;
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
Thanks for your time.
by the definition of your program sad numbers will cause your program to run forever
Conversely, if the process is repeated indefinitely
You need to add a stopping condition, like if I have looped for 1000 times, or if you hit a well known non terminating number (like 4) (is there a definite list of these? I dont know)
I find this solution tested and working..
Thanks for your time and I am sorry for my vagueness.
Every advice about this solution would be welcome
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void happy( char * A, int n);
int numPlaces (long n);
int happynum = 0;
int main(void)
{
long A,B;
int npA;
char *Ap;
printf("Give 2 Numbers\n");
scanf("%li %li",&A,&B);
npA = numPlaces(A);
Ap = malloc(npA);
//Search for happy numbers from A to B
do{
sprintf(Ap, "%ld", A);
happy(Ap,npA);
if (happynum ==1)
printf("%s\n",Ap);
A++;
if ( npA < numPlaces(A) )
{
npA++;
Ap = realloc(Ap, npA);
}
}while( A <= B);
}
//Finds happy numbers
void happy( char * A, int n)
{
//Basic Condition
if ( n == 1)
{
if (A[0] == '3' || A[0] == '6' || A[0] == '9')
{
happynum = 0;
}
else
{
happynum = 1;
}
return;
}
long sum = 0;
char * sumA;
int nsum;
int Ai;
//Sum the squares of the current number
for(int i = 0 ; i < n;i++)
{
Ai = (int)(A[i]-48);
sum = sum + (Ai*Ai);
}
nsum = numPlaces (sum);
sumA = malloc(nsum);
sprintf(sumA, "%li", sum);
happy(sumA,nsum);
free(sumA);
}
//Count digits of a number
int numPlaces (long n)
{
if (n < 0) return 0;
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
Your code uses some questionable practices. Yoe may be misguided because you are concerned about performance and memory usage.
When you allocate memory for the string, you forget to allocate one character for the null terminator. But you shouldn't be allocating, re-allocating and freeing constantly anyway. Dynamic memory allocation is expensive compared to your other operations.
Your limits are long, which may be a 32-bit or 64-bit signed integer, depending on your platform. The maximum number that can be represented with e 64-bit signed integer is 9,223,372,036,854,775,807. This is a number with 19 digits. Add one for the null terminator and one for a possible minus sign, so that overflow won't hurt, you and use a buffer of 21 chars on the stack.
You probably shouldn't be using strings inthe first place. Use the basic code to extract the digits: Split off the digit by taking the remainder of a division by 10. Then divide by 10 until you get zero. (And if you use strings with a fixed buffer size, as described above, you don't have to calculate the difits separately: sprintf returns the number of characters written to the string.
Your functions shouldn't be recursive. A loop is enough. As pm100 has noted, you need a termination criterion: You must keep track of the numbers that you have already visited. Each recursive call creates a new state; it is easier to keep an array, that can be repeatedly looked at in a loop. When you see a number that you have already seen (other than 1, of course), your number is sad.
Happy and sad numbers have this property that when your sum of squares is a number with a known happiness, the original number has this happiness, too. If you visit a known das number, the original number is sad. If you visit a known happy number, the original number is happy.
The limits of your ranges may ba large, but the sum of square digits is not large; it can be at most the number of digits times 81. In particular:
type max. number number of max. square sum dss
int 2,147,483,647 1,999,999,999 730
uint 4,294,967,295 3,999,999,999 738
long 9,223,372,036,854,775,807 8,999,999,999,999,999,999 1522
ulong 18,446,744,073,709,55,1616 9,999,999,999,999,999,999 1539
That means that when you take the sum of digit squares of an unsigned long, you will get a number that is smaller than 1540. Create an array of 1540 entries and mark all known happy numbers with 1. Then you can reduce your problem to taking the sum of digit squares once and then looking up the happiness of the number in this array.
(You can do the precalculation of the array once when you start the program.)

Weird Output with first case integer

Here are two functions below that compile perfectly but I seem to be getting a weird error with the very first inputted integer. I have tried debugging in GDB but when it's only the first inputted value that is having this weird error, then it makes things complicated.
#include <stdio.h>
#include "Assg9.h"
#include <stdlib.h>
#include <assert.h>
#include <math.h>
void getPrimes(int usernum, int* count, int** array){
(*count) = (usernum - 1);
int sieve[usernum-1], primenums = 0, index, fillnum, multiple;
for(index = 0, fillnum = 2; fillnum <= usernum; index++, fillnum++){
sieve[index] = fillnum;
}
for (; primenums < sqrt(usernum); primenums++)
{
if (sieve[primenums] != 0){
for (multiple = primenums + (sieve[primenums]); multiple < usernum - 1; multiple += sieve[primenums])//If it is not crossed out it starts deleting its multiples.
{
if(sieve[multiple]) {
--(*count);
sieve[multiple] = 0;
}
}
}
}
int k;
for (k = 0; k < usernum; k++)
if (sieve[k] != 0)
{
printf("%d ", sieve[k]);
}
*array = malloc(sizeof(int) * (usernum +1));
assert(array);
(*array) = sieve;
}
void writeToOutputFile(FILE *fpout, const int *array, int n, int count){
int i;
fprintf(fpout, "There are %d prime numbers less than or equal to %d \n", count, n);
for(i = 0; i < count; i++)
{
if(*(array + i) != 0){
fprintf(fpout, "%d ", *(array + i));
}
}
}
Our Output:
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2 32664
Do you want to try again? Press Y for Yes and N for No: y
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2
Do you want to try again? Press Y for Yes and N for No: n
Good bye. Have a nice day
Expected output should obviously just display 2. This is the case for any integer from 2-2000 for the very first inputted integer. The very last, or last 2, prime numbers print very large numbers, sometimes even negative numbers. I have no clue why, but after the first inputted value everything works perfectly. Tried debugging this with GDB like crazy but with no luck. Would really appreciate someone's help for this bizarre error
You aren't initializing the sieves array to 0s. So you're looping from 0 to usernum-1, printing out every number that isn't a 0. Since you didn't initialize the array, the 2nd element is a random value and is being printed out
This code is a problem:
(*array) = sieve;
You are are assigning the address of sieve, a temporary local array, to *array. You need to copy the array contents instead.
Are you also this person who has asked three questions about identical code?

Resources