Esempio n. 1
0
int main(void) {
	/*this program computes primes*/
	bint prime[MAX_PRIMES];
	int primes;

	bint testprime,zero;

	/* we have to enter at least 1 prime */
	primes=1;
	uint_to_bint(2,&prime[primes-1]);

	/*make zero 0*/
	uint_to_bint(0,&zero);


	/*we start testing at the last prime in table +1*/
	testprime=prime[primes-1];

	printf("Prime generator:\n");
	printf("Primes number 2-%d\n",MAX_PRIMES);
	while(primes<MAX_PRIMES) {
		bint testsqrt;
		int primeptr;
		int is_a_prime=1;

		bint_inc(&testprime);              /* increase*/
		bint_sqrt(&testprime,&testsqrt);   /* compute square root of
						      test - this speed up the
						      algorithm due to the fact
						      we dont have to test
						      division more than to the
						      square root of the number
						    */
		bint_inc(&testsqrt);
		primeptr=0;

		while(primeptr<primes &&
		      is_a_prime &&
		      bint_cmp(&prime[primeptr],&testsqrt)<=0) {
			bint remainder;

			bint_mod(&testprime,&prime[primeptr],&remainder);
			if(bint_cmp(&remainder,&zero)==0)
				is_a_prime=0;
			else
				primeptr++;
		}
		if(is_a_prime) {
			/*got a prime*/
			char s[100];
			prime[primes++]=testprime;
			/*convert to string*/
			bint_to_string(&testprime,s);
			/*print out the prime*/
			printf("%4.4d: %12.12s  ",primes,s);
		}
	}
	putchar('\n');
	return 0;/*Ok*/
}
Esempio n. 2
0
t_bint * bint_add_dst(t_bint ** dst, t_bint * a, t_bint * b) {

	int a_zero = bint_is_zero(a);
	int b_zero = bint_is_zero(b);

	//if a and b are 0
	if (a_zero && b_zero) {
		//return 0
		return (BINT_ZERO);
	}

	if (a_zero) {
		return (bint_clone(b));
	}

	if (b_zero) {
		return (bint_clone(a));
	}

	//the size to store the result
	size_t size = (a == NULL || a_zero) ? b->size : (b == NULL || b_zero) ? a->size : (a->size > b->size) ? a->size : b->size;

	//ensure that 'dst' bint has the given size
	t_bint * r = bint_ensure_size(dst, size);

	//if allocation failed
	if (r == NULL) {
		return (NULL);
	}

	//do the addition, r has now a correct size to store the result

	//compare the two integers
	int cmp = bint_cmp(a, b);

	//if a == b, then return 2 * a
	if (cmp == 0) {
		//dst = a << 1 = 2 * a
		bint_shift_left_dst(&r, a, 1);
		return (r);
	}

	//else, if a < b
	if (cmp < 0) {
		//swap them, so we always then have a > b
		t_bint * tmp = a;
		a = b;
		b = tmp;
	}

	//' a + (-b) ' becomes ' a - b '
	//notice that the case '(-a) + b ' becoming ' b - a' is impossible here: a > b
	if (a->sign == 1 && b->sign == -1) {
		//TODO : a - abs(b)
		puts("warning: addition sign issue");
	} else {
		//a and b have the same size, and a > b
		//set the sign
		r->sign = a->sign;

		//finally do the addition
		_bint_add_dst_raw(r, a, b);
	}

	//return it
	return (r);
}