numtheory.c 12.7 KB
Newer Older
Morten Welinder's avatar
Morten Welinder committed
1 2 3 4 5 6
/*
 * Number Theory Plugin
 *
 * Author:
 *    Marko R. Riedel (mriedel@neuearbeit.de)    [Functions]
 *    Morten Welinder (terra@diku.dk)            [Plugin framework]
7
 *    Brian J. Murrell (brian@interlinx.bc.ca)	 [Bitwise operators]
Morten Welinder's avatar
Morten Welinder committed
8
 */
9 10
#include <gnumeric-config.h>
#include <gnumeric.h>
Morten Welinder's avatar
Morten Welinder committed
11
#include <glib.h>
12
#include <libgnome/gnome-i18n.h>
Morten Welinder's avatar
Morten Welinder committed
13

14 15
#include "func.h"
#include "plugin.h"
16
#include "plugin-util.h"
17
#include "module-plugin-defs.h"
18
#include "value.h"
Morten Welinder's avatar
Morten Welinder committed
19 20
#include <limits.h>

21
GNUMERIC_MODULE_PLUGIN_INFO_DECL;
22

Morten Welinder's avatar
Morten Welinder committed
23
#ifndef WORD_BIT
24
#define WORD_BIT ((int)(sizeof (int) * CHAR_BIT))
Morten Welinder's avatar
Morten Welinder committed
25
#endif
Morten Welinder's avatar
Morten Welinder committed
26 27 28

#define OUT_OF_BOUNDS "#LIMIT!"

29

Morten Welinder's avatar
Morten Welinder committed
30 31 32 33 34 35
/* ------------------------------------------------------------------------- */

static int
intpow (int p, int v)
{
	int temp;
36

Morten Welinder's avatar
Morten Welinder committed
37 38 39
	if (v == 0) return 1;
	if (v == 1) return p;

40 41 42
	temp = intpow (p, v / 2);
	temp *= temp;
	return (v % 2) ? temp * p : temp;
Morten Welinder's avatar
Morten Welinder committed
43 44
}

45 46
#define PTABLE_CHUNK 64
#define ITHPRIME_LIMIT 1000000
47
static gint *prime_table = NULL;
Morten Welinder's avatar
Morten Welinder committed
48

49 50
/* Calculate the i-th prime.  Returns TRUE on error.  */
static gboolean
Morten Welinder's avatar
Morten Welinder committed
51 52 53 54 55
ithprime (int i, int *res)
{
	static int computed = 0;
	static int allocated = 0;

56
	if (i < 1 || i > ITHPRIME_LIMIT)
57
		return TRUE;
Morten Welinder's avatar
Morten Welinder committed
58

59 60
	if (i > computed) {
		int candidate;
Morten Welinder's avatar
Morten Welinder committed
61

62 63 64 65 66 67 68
		if (i > allocated) {
			g_assert (PTABLE_CHUNK >= 2);
			allocated = MAX (i, allocated + PTABLE_CHUNK);
			prime_table = g_renew (int, prime_table, allocated);
			if (computed == 0) {
				prime_table[computed++] = 2;
				prime_table[computed++] = 3;
Morten Welinder's avatar
Morten Welinder committed
69
			}
70
		}
Morten Welinder's avatar
Morten Welinder committed
71

72 73
		candidate = prime_table[computed - 1];
		/*
Morten Welinder's avatar
Typo.  
Morten Welinder committed
74
		 * Note, that the candidate is odd since we filled in the first
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
		 * two prime numbers.
		 */
		while (i > computed) {
			gboolean prime = TRUE;
			int j;
			candidate += 2;  /* Skip even candidates.  */

			for (j = 1; prime_table[j] * prime_table[j] <= candidate; j++)
				if (candidate % prime_table[j] == 0) {
					prime = FALSE;
					break;
				}

			if (prime)
				prime_table[computed++] = candidate;
Morten Welinder's avatar
Morten Welinder committed
90 91 92
		}
	}

93
	*res = prime_table[i - 1];
94
	return FALSE;
Morten Welinder's avatar
Morten Welinder committed
95 96
}

97 98 99 100 101
/*
 * A function useful for computing multiplicative aritmethic functions.
 * Returns TRUE on error.
 */
static gboolean
Morten Welinder's avatar
Morten Welinder committed
102 103 104
walk_factorization (int n, void *data,
		    void (*walk_term) (int p, int v, void *data))
{
105
	int index = 1, p = 2, v;
Morten Welinder's avatar
Morten Welinder committed
106 107

	while (n > 1 && p * p <= n) {
108 109
		if (ithprime (index, &p))
			return TRUE;
Morten Welinder's avatar
Morten Welinder committed
110 111

		v = 0;
112 113
		while (n % p == 0) {
			v++;
Morten Welinder's avatar
Morten Welinder committed
114 115 116 117
			n /= p;
		}

		if (v) {
118
			/* We found a prime factor, p, with arity v.  */
Morten Welinder's avatar
Morten Welinder committed
119 120 121 122 123 124 125
			walk_term (p, v, data);
		}

		index++;
	}

	if (n > 1) {
126 127 128 129
		/*
		 * A number, n, with no factors from 2 to sqrt (n) is a
		 * prime number.  The arity is 1.
		 */
Morten Welinder's avatar
Morten Welinder committed
130 131
		walk_term (n, 1, data);
	}
132 133

	return FALSE;
Morten Welinder's avatar
Morten Welinder committed
134 135
}

136 137 138 139 140 141
/*
 * Returns -1 (out of bounds), or #primes <= n
 */
static int
compute_nt_pi (int n)
{
Morten Welinder's avatar
Morten Welinder committed
142
	int lower = 2, upper = 4, mid, p = 7;
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

	if (n <= 1)
		return 0;

	if (n < 4)
		return n - 1;

	while (p < n) {
		lower = upper;
		upper *= 2;
		if (ithprime (upper, &p))
			return -1;
	}

	while (upper - lower > 1) {
		mid = (lower + upper) / 2;
		ithprime (mid, &p);

		if (p < n)
			lower = mid;
		else if (p > n)
			upper = mid;
		else
			return mid;
	}

	ithprime (upper, &p);
	return (p == n) ? lower + 1 : lower;
}


/*
 * Returns -1 (out of bounds), 0 (non-prime), or 1 (prime).
 */
static int
isprime (int n)
{
	int i = 1, p = 2;

	if (n <= 1)
		return 0;

	for (i = 1; p * p <= n; i++) {
		if (ithprime (i, &p))
			return -1;
		if (n % p == 0)
			return 0;
	}

	return 1;
}

Morten Welinder's avatar
Morten Welinder committed
195 196
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
197
static const char *help_phi = {
Morten Welinder's avatar
Morten Welinder committed
198 199 200 201
	N_("@FUNCTION=NT_PHI\n"
	   "@SYNTAX=NT_PHI(n)\n"
	   "@DESCRIPTION="
	   "The NT_PHI function calculates the number of integers less "
202
	   "than or equal to @n that are relatively prime to @n.\n"
Morten Welinder's avatar
Morten Welinder committed
203 204 205
	   "This function only takes one argument."
	   "\n"
	   "@EXAMPLES=\n"
206
	   "@SEEALSO=NT_D, ITHPRIME, NT_SIGMA")
Morten Welinder's avatar
Morten Welinder committed
207 208
};

209 210 211 212 213 214
static void
walk_for_phi (int p, int v, void *data)
{
	*((int *)data) *= intpow (p, v - 1) * (p - 1);
}

Morten Welinder's avatar
Morten Welinder committed
215 216 217 218 219 220 221 222
static Value *
gnumeric_phi (FunctionEvalInfo *ei, Value **args)
{
	int n, phi = 1;

	n = value_get_as_int (args [0]);
	if (n < 1)
		return value_new_error (ei->pos, gnumeric_err_NUM);
223 224

	if (walk_factorization (n, &phi, walk_for_phi))
Morten Welinder's avatar
Morten Welinder committed
225 226 227 228 229
		return value_new_error (ei->pos, OUT_OF_BOUNDS);

	return value_new_int (phi);
}

230 231
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
232
static const char *help_nt_mu = {
233 234 235
	N_("@FUNCTION=NT_MU\n"
	   "@SYNTAX=NT_MU(n)\n"
	   "@DESCRIPTION="
236
	   "The NT_MU function (Möbius mu function) returns \n"
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
	   "0  if @n is divisible by the square of a prime .\n"
	   "Otherwise it returns: \n"
	   "-1 if @n has an odd  number of different prime factors .\n"
	   "1  if @n has an even number of different prime factors .\n"
	   "If @n=1 it returns 1\n"
	   "\n"
	   "@EXAMPLES=\n"
	   "@SEEALSO=NT_D, ITHPRIME, NT_PHI")
};

static void
walk_for_mu (int p, int v, void *data)
{
	*((int *)data) = (v >= 2) ?  0 : - *((int *)data) ;
}

static Value *
gnumeric_nt_mu (FunctionEvalInfo *ei, Value **args)
{
	int n, mu = 1;

	n = value_get_as_int (args [0]);
	if (n < 1)
		return value_new_error (ei->pos, gnumeric_err_NUM);

	if (walk_factorization (n, &mu, walk_for_mu))
		return value_new_error (ei->pos, OUT_OF_BOUNDS);

	return value_new_int (mu);
}


269
/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
270

Morten Welinder's avatar
Morten Welinder committed
271
static const char *help_d = {
Morten Welinder's avatar
Morten Welinder committed
272 273 274
	N_("@FUNCTION=NT_D\n"
	   "@SYNTAX=NT_D(n)\n"
	   "@DESCRIPTION="
275
	   "The NT_D function calculates the number of divisors of @n.\n"
Morten Welinder's avatar
Morten Welinder committed
276 277 278
	   "This function only takes one argument."
	   "\n"
	   "@EXAMPLES=\n"
279
	   "@SEEALSO=ITHPRIME, NT_PHI, NT_SIGMA")
Morten Welinder's avatar
Morten Welinder committed
280 281
};

282 283 284 285 286 287
static void
walk_for_d (int p, int v, void *data)
{
	* (int *) data *= (v + 1);
}

Morten Welinder's avatar
Morten Welinder committed
288 289 290 291 292 293 294 295
static Value *
gnumeric_d (FunctionEvalInfo *ei, Value **args)
{
	int n, d = 1;

	n = value_get_as_int (args [0]);
	if (n < 1)
		return value_new_error (ei->pos, gnumeric_err_NUM);
296 297

	if (walk_factorization (n, &d, walk_for_d))
Morten Welinder's avatar
Morten Welinder committed
298 299 300 301 302
		return value_new_error (ei->pos, OUT_OF_BOUNDS);

	return value_new_int (d);
}

303
/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
304

Morten Welinder's avatar
Morten Welinder committed
305
static const char *help_sigma = {
Morten Welinder's avatar
Morten Welinder committed
306 307 308
	N_("@FUNCTION=NT_SIGMA\n"
	   "@SYNTAX=NT_SIGMA(n)\n"
	   "@DESCRIPTION="
309
	   "The NT_SIGMA function calculates the sum of the divisors of @n.\n"
Morten Welinder's avatar
Morten Welinder committed
310 311 312
	   "This function only takes one argument."
	   "\n"
	   "@EXAMPLES=\n"
313
	   "@SEEALSO=NT_D, ITHPRIME, NT_PHI")
Morten Welinder's avatar
Morten Welinder committed
314 315
};

316 317 318
static void
walk_for_sigma (int p, int v, void *data)
{
319
	* (int *) data *=
320 321 322
		  ( v == 1 ? p + 1 : (intpow (p, v + 1) - 1) / (p - 1) );
}

Morten Welinder's avatar
Morten Welinder committed
323 324 325 326 327 328 329 330
static Value *
gnumeric_sigma (FunctionEvalInfo *ei, Value **args)
{
	int n, sigma = 1;

	n = value_get_as_int (args [0]);
	if (n < 1)
		return value_new_error (ei->pos, gnumeric_err_NUM);
331 332

	if (walk_factorization (n, &sigma, walk_for_sigma))
Morten Welinder's avatar
Morten Welinder committed
333 334 335 336 337
		return value_new_error (ei->pos, OUT_OF_BOUNDS);

	return value_new_int (sigma);
}

338 339
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
340
static const char *help_ithprime = {
341 342
	N_("@FUNCTION=ITHPRIME\n"
	   "@SYNTAX=ITHPRIME(i)\n"
Morten Welinder's avatar
Morten Welinder committed
343
	   "@DESCRIPTION="
344
	   "The ITHPRIME function returns the @ith prime.\n"
Morten Welinder's avatar
Morten Welinder committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358
	   "This function only takes one argument."
	   "\n"
	   "@EXAMPLES=\n"
	   "@SEEALSO=NT_D, NT_SIGMA")
};

static Value *
gnumeric_ithprime (FunctionEvalInfo *ei, Value **args)
{
	int i, p;

	i = value_get_as_int (args [0]);
	if (i < 1)
		return value_new_error (ei->pos, gnumeric_err_NUM);
359 360

	if (ithprime (i, &p))
Morten Welinder's avatar
Morten Welinder committed
361 362 363 364 365 366 367
		return value_new_error (ei->pos, OUT_OF_BOUNDS);

	return value_new_int (p);
}

/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
368
static const char *help_isprime = {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
	N_("@FUNCTION=ISPRIME\n"
	   "@SYNTAX=ISPRIME(i)\n"
	   "@DESCRIPTION="
	   "The ISPRIME function returns TRUE if @i is prime "
	   "and FALSE otherwise.\n"
	   "This function only takes one argument."
	   "\n"
	   "@SEEALSO=ITHPRIME, NT_D, NT_SIGMA")
};

static Value *
gnumeric_isprime (FunctionEvalInfo *ei, Value **args)
{
	int i, yesno;

	i = value_get_as_int (args [0]);
	yesno = isprime (i);
	if (yesno == -1)
		return value_new_error (ei->pos, OUT_OF_BOUNDS);
	else
		return value_new_bool (yesno);
}

/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
394
static const char *help_nt_pi = {
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	N_("@FUNCTION=NT_PI\n"
	   "@SYNTAX=NT_PI(n)\n"
	   "@DESCRIPTION="
	   "The NT_PI function returns the number of primes "
	   "less than or equal to @n.\n"
	   "This function only takes one argument."
	   "\n"
	   "@SEEALSO=ITHPRIME, NT_PHI, NT_D, NT_SIGMA")
};

static Value *
gnumeric_nt_pi (FunctionEvalInfo *ei, Value **args)
{
	int n, pi;

	n = value_get_as_int (args [0]);
	pi = compute_nt_pi (n);

	if (pi == -1)
		return value_new_error (ei->pos, OUT_OF_BOUNDS);
	else
		return value_new_int (pi);
}

/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
421
static const char *help_bitor = {
422 423 424 425 426 427 428 429 430
	N_("@FUNCTION=BITOR\n"
	   "@SYNTAX=BITOR(a,b)\n"
	   "@DESCRIPTION="
	   "The BITOR function returns bitwise or-ing of its arguments.\n"
	   "\n"
	   "@EXAMPLES=\n"
	   "@SEEALSO=BITXOR,BITAND")
};

431 432 433 434
static Value *
func_bitor (FunctionEvalInfo *ei, Value *argv [])
{
        return value_new_int (value_get_as_int (argv [0]) |
435 436 437
			      value_get_as_int (argv [1]));
}

438 439
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
440
static const char *help_bitxor = {
441 442 443 444 445 446 447 448 449
	N_("@FUNCTION=BITXOR\n"
	   "@SYNTAX=BITXOR(a,b)\n"
	   "@DESCRIPTION="
	   "The BITXOR function returns bitwise exclusive or-ing of its arguments.\n"
	   "\n"
	   "@EXAMPLES=\n"
	   "@SEEALSO=BITOR,BITAND")
};

450 451 452 453 454
static Value *
func_bitxor (FunctionEvalInfo *ei, Value *argv [])
{
        return value_new_int (value_get_as_int (argv [0]) ^
			      value_get_as_int (argv [1]));
455 456
}

457 458
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
459
static const char *help_bitand = {
460 461 462 463 464 465 466 467 468 469
	N_("@FUNCTION=BITAND\n"
	   "@SYNTAX=BITAND(a,b)\n"
	   "@DESCRIPTION="
	   "The BITAND function returns bitwise and-ing of its arguments.\n"
	   "\n"
	   "@EXAMPLES=\n"
	   "@SEEALSO=BITOR,BITXOR")
};


470 471 472 473
static Value *
func_bitand (FunctionEvalInfo *ei, Value *argv [])
{
        return value_new_int (value_get_as_int (argv [0]) &
474
			      value_get_as_int (argv [1]));
475 476
}

477 478
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
479
static const char *help_bitlshift = {
480 481 482 483 484 485 486 487 488 489
	N_("@FUNCTION=BITLSHIFT\n"
	   "@SYNTAX=BITLSHIFT(x,n)\n"
	   "@DESCRIPTION="
	   "The BITLSHIFT function returns @x bit-shifted left by @n bits.\n"
	   "If @n is negative, a right shift will in effect be performed.\n"
	   "\n"
	   "@EXAMPLES=\n"
	   "@SEEALSO=BITRSHIFT")
};

490 491 492
static Value *
func_bitlshift (FunctionEvalInfo *ei, Value *argv [])
{
493 494 495 496 497 498 499 500 501
	int l = value_get_as_int (argv [0]);
	int r = value_get_as_int (argv [1]);

	if (r >= WORD_BIT || r <= -WORD_BIT)
		return value_new_int (0);  /* All bits shifted away.  */
	else if (r < 0)
		return value_new_int (l >> (-r));
	else
		return value_new_int (l << r);
502 503
}

504 505
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
506
static const char *help_bitrshift = {
507 508 509 510 511 512 513
	N_("@FUNCTION=BITRSHIFT\n"
	   "@SYNTAX=BITRSHIFT(x,n)\n"
	   "@DESCRIPTION="
	   "The BITRSHIFT function returns @x bit-shifted right by @n bits.\n"
	   "If @n is negative, a left shift will in effect be performed.\n"
	   "\n"
	   "@EXAMPLES=\n"
514
	   "@SEEALSO=BITLSHIFT")
515 516
};

517 518 519
static Value *
func_bitrshift (FunctionEvalInfo *ei, Value *argv [])
{
520 521 522 523 524 525 526 527 528
	int l = value_get_as_int (argv [0]);
	int r = value_get_as_int (argv [1]);

	if (r >= WORD_BIT || r <= -WORD_BIT)
		return value_new_int (0);  /* All bits shifted away.  */
	else if (r < 0)
		return value_new_int (l << (-r));
	else
		return value_new_int (l >> r);
529 530 531 532
}

/* ------------------------------------------------------------------------- */

533 534
void
plugin_cleanup (void)
Morten Welinder's avatar
Morten Welinder committed
535
{
536
	g_free (prime_table);
537
	prime_table = NULL;
Morten Welinder's avatar
Morten Welinder committed
538 539
}

540
const ModulePluginFunctionInfo num_theory_functions[] = {
Jukka Pekka's avatar
Jukka Pekka committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554
	{"ithprime", "f", "number", &help_ithprime,
	 &gnumeric_ithprime, NULL, NULL, NULL },
	{"nt_phi",   "f", "number", &help_phi,
	 &gnumeric_phi,      NULL, NULL, NULL },
	{"nt_d",     "f", "number", &help_d,
	 &gnumeric_d,        NULL, NULL, NULL },
	{"nt_sigma", "f", "number", &help_sigma,
	 &gnumeric_sigma,    NULL, NULL, NULL },
	{"isprime",  "f", "number", &help_isprime,
	 &gnumeric_isprime,  NULL, NULL, NULL },
	{"nt_pi",    "f", "number", &help_nt_pi,
	 &gnumeric_nt_pi,    NULL, NULL, NULL },
	{"nt_mu",    "f", "number", &help_nt_mu,
	 &gnumeric_nt_mu,    NULL, NULL, NULL },
555 556 557
	{NULL}
};

558
const ModulePluginFunctionInfo bitwise_functions[] = {
Jukka Pekka's avatar
Jukka Pekka committed
559 560 561 562 563 564 565 566 567 568
	{"bitor",     "ff", "A,B", &help_bitor,
	 &func_bitor,     NULL, NULL, NULL },
	{"bitxor",    "ff", "A,B", &help_bitxor,
	 &func_bitxor,    NULL, NULL, NULL },
	{"bitand",    "ff", "A,B", &help_bitand,
	 &func_bitand,    NULL, NULL, NULL },
	{"bitlshift", "ff", "X,N", &help_bitlshift,
	 &func_bitlshift, NULL, NULL, NULL },
	{"bitrshift", "ff", "N,N", &help_bitrshift,
	 &func_bitrshift, NULL, NULL, NULL },
569 570
	{NULL}
};