Arithmetic-Derivative/arithmetic_derivative.c

57 lines
1.4 KiB
C
Raw Normal View History

2016-12-09 22:14:05 +01:00
#include <stdio.h>
2016-12-12 15:01:54 +01:00
long long derive (long long n);
void split (long long value, long long *a, long long *b);
2016-12-09 22:14:05 +01:00
int main () {
2016-12-12 15:01:54 +01:00
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');
2016-12-09 22:14:05 +01:00
}
2016-12-12 15:01:54 +01:00
// 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;
}
2016-12-09 22:14:05 +01:00
}
2016-12-12 15:01:54 +01:00
// n = a * b
void split (long long value, long long *a, long long *b) {
long long i = 2;
int stop = 0;
2016-12-10 12:26:56 +01:00
do {
if (value % i == 0) {
*a = i;
*b = value / *a;
2016-12-12 15:01:54 +01:00
stop++;
2016-12-09 22:14:05 +01:00
}
2016-12-10 12:26:56 +01:00
i++;
2016-12-12 15:01:54 +01:00
} while (stop == 0);
2016-12-09 22:14:05 +01:00
}