Arithmetic-Derivative/arithmetic_derivative.c

57 lines
1.4 KiB
C

#include <stdio.h>
long long derive (long long n);
void split (long long value, long long *a, long long *b);
int main () {
long long n, res;
int sgn;
char again;
do {
sgn = 1;
printf ("Enter an integer: ");
scanf ("%lli", &n);
if (n < 0)
sgn = -1;
if ( sgn * n > 9999999999999999)
printf ("Warning! Number too big. The result could be wrong\n");
res = derive (sgn * n); // derive (abs (n))
res = sgn * res; // (-n)' = -(n')
printf ("The arithmetic derivative of %lli is: %lli", n, res);
getchar ();
printf ("\nAgain? [y/n] ");
scanf ("%c", &again);
} while (again != 'n');
}
// if n=ab (a and b > 1) -> n'=a'b + ab'
long long derive (long long n){
long long a = 1, b = 1;
switch (n) {
case 0: return 0; break; // 0' = 0
case 1: return 0; break; // 1' = 0;
default:
split (n, &a, &b); // n = a * b
if (b > 1) // if n is not a prime
n = derive (a) * b + a * derive (b);
else
n = 1; // if n is a prime
return n;
break;
}
}
// n = a * b
void split (long long value, long long *a, long long *b) {
long long i = 2;
int stop = 0;
do {
if (value % i == 0) {
*a = i;
*b = value / *a;
stop++;
}
i++;
} while (stop == 0);
}