Unité IN3S02 - TD2
Corrigé
2.1- Factorielle (*)
/**
*
@param n natural number
*/
public static int
factorielle(int n) {
int f = 1 ;
for ( ; n > 1 ; n-- ) f = f * n ;
return f ;
}
2.2- Pgcd (*)
/**
* @param a and b natural numbers
*/
public static int pgcd(int a, int b) {
int c ;
while
( b != 0 ) {
c = b ;
b = a % b ;
a = c ;
}
return a ;
}
2.3- Racine cubique (*)
public static double
cubeRoot(double
x) {
if ( x == 0 ) return 0 ;
final double EPSILON = 1E-5 ;
double oldroot ;
double root = 1 ;
do {
oldroot = root ;
root = (2*root + x/(root*root)) / 3 ;
} while ( Math.abs((root - oldroot) / root) >
EPSILON ) ;
return root ;
}
2.4- Fibonacci (*)
/**
* @param n
> 0
*/
public static int fibonacci(int
n) {
int f=1, g=0
;
for ( ; n > 1 ; n-- ) {
f = f + g ;
g = f - g ;
}
return f ;
}
2.5- Nombre parfait (*)
/**
*
@param 0 <= i <= j
* @return first perfect number in [i, j], or 0
otherwise
*/
public static int
perfectNumber(int i,
int j) {
boolean isPerfect = false ;
int k ;
for ( k = Math.max(i,2) ; k <= j && ! isPerfect ;
k++
) {
int sumDividors = 1 ;
/* Solution 1 */
for ( int d = 2; d <= k/2; d++ ) {
if ( k % d == 0 )
sumDividors += d ;
/* Solution 2 */
// int d = 2 ;
// for ( ; d < Math.sqrt(k);
d++ ) {
// if ( k % d == 0 )
sumDividors += d + (k / d);
// if ( d*d == k) sumDividors
+=d ;
}
isPerfect = ( k == sumDividors ) ;
}
if (isPerfect) return k-1 ;
return 0 ;
}
/**
* @param 0
<= i <= j
*/
public static void
printPerfectNumbers(int i, int j) {
while
(i <= j) {
i = perfectNumber(i, j);
if ( i == 0 ) i = j ;
else System.out.println(i);
i++ ;
}
}
2.6- Sinus (*)
/**
* @param x must be near zero (typically |x| < 0.5)
*/
public static double
sinus(double x) {
final double
EPSILON = 1e-5;
double t = x ; // current term
double pt ; // previous term
double s = t ; // sum
int n = 1 ; // n
do {
pt = t ;
n = n + 2 ;
t = t * (-x*x)/(n*(n-1)) ;
s += t ;
} while ( Math.abs(t-pt)/pt > EPSILON ) ;
return s ;
}
2.7- Conversion octal vers décimal (**)
/**
* @param n
octal >= 0
*/
public static int
octalToDecimal(int
n) {
int dec
= 0 ;
int weight = 1 ;
while ( n != 0 ) {
dec += (n % 10)*weight ;
weight *= 8 ;
n = n / 10 ;
}
return dec ;
}