Php algo td3
Aller à la navigation
Aller à la recherche
Sujet
Partie A
On sait que :
- dividende = (quotient x diviseur) + reste
- dividende // diviseur → quotient entier
- dividende % diviseur → reste
Exercice 1
FONCTION decimal_octal(n)
VAR
tmp, resultat : liste d'entiers
fin: booléen
quotient, i, j : entier
fin <- faux
quotient <- n
i <- 0
TANT QUE fin = faux
tmp[i] = quotient % 8
quotient = quotient // 8
SI quotient = 0
fin <- vrai
FIN SI
i++
FIN TANT QUE
j <- i
TANT QUE i > 0
resultat[j-i] = tmp[i]
i--
FIN TANT QUE
RETOURNE resultat
FIN FONCTION
Exercice 2
FONCTION octal_decimal(n)
VAR
resultat, i : entier
i <- len(n)
POUR TOUT m de n FAIRE
resultat += m * (8**i)
i--
FIN POUR
RETOURNE resultat
FIN FONCTION
Partie B
Exercice 3
function decimal_octal($n) {
$resultat = array ();
$fin = false;
$quotient = $n;
while ( ! $fin ) {
$resultat [] = $quotient % 8;
$quotient = floor ( $quotient / 8 );
if ($quotient == 0) {
$fin = true;
}
}
return array_reverse ( $resultat );
}
Exercice 4
function octal_decimal($n) {
$resultat = 0;
$i = sizeof ( $n )-1;
foreach ( $n as $m ) {
$resultat += $m * pow ( 8, $i );
$i --;
}
return $resultat;
}
Exercice 5
<?php
function decimal_octal($n) {
$resultat = array ();
$fin = false;
$quotient = $n;
while ( ! $fin ) {
$resultat [] = $quotient % 8;
$quotient = floor ( $quotient / 8 );
if ($quotient == 0) {
$fin = true;
}
}
return array_reverse ( $resultat );
}
function octal_decimal($n) {
$resultat = 0;
$i = sizeof ( $n ) - 1;
foreach ( $n as $m ) {
$resultat += $m * pow ( 8, $i );
$i --;
}
return $resultat;
}
function main($argv) {
/* Récupération du nombre décimal */
if (sizeof ( $argv ) < 2) {
echo "Spécifier un nombre en paramètre et un un base (decimal (d) octal (o)) !";
exit ( 1 );
}
/* Lecture du nombre */
$nombre = $argv [1];
/* Lecture de la base */
$base = $argv [2];
/* Convertion du nombre */
if ($base == 'd') {
$decimal = octal_decimal ( str_split ( $nombre ) );
echo "Le nombre " . $nombre . " en base 8 s'écrit " . $decimal . " en base 10.";
} else if ($base == 'o') {
$octal = "";
foreach ( decimal_octal ( $nombre ) as $digit ) {
$octal .= $digit;
}
echo "Le nombre " . $nombre . " en base 10 s'écrit " . $octal . " en base 8.";
}
echo "\n";
}
main ( $argv );
?>
Exécution
# php -f TD3.php 1205 o Le nombre 1205 en base 10 s'écrit 2265 en base 8. # php -f TD3.php 2265 d Le nombre 2265 en base 8 s'écrit 1205 en base 10.