Les Snippets

Connexion

Somme des chiffres d'un nombre

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 10/05/2007 10:58:04 et initié par Shakan972 [Liste]
Date de mise à jour : 09/11/2007 15:09:17
Vue : 13515
Catégorie(s) : Maths
Langages dispo pour ce code :
- Python
- Python
- C
- VB6
- C
- Delphi 5
- Delphi 5
- ObjectiveCaml
- ActionScript Flash
- PHP 3, PHP 4, PHP 5
- Perl
- VB6, VBA
- VB 2005



Langage : Python
Date ajout : 10/05/2007
Posté par Shakan972 [Liste]
def SommeChiffres(nbre):     somme=0     while nbre!=0:         somme=somme+(nbre%10)         nbre=nbre/10     return somme
Langage : Python
Date ajout : 12/05/2007
Posté par pacificator [Liste]
sum([int(i) for i in str(nbre)])
Langage : C
Date ajout : 15/05/2007
Posté par BruNews [Liste]
DateMAJ : 18/05/2007

Remarque :
__declspec(naked) DWORD __fastcall bnsumint(int inum)
{
  __asm {
    test ecx, ecx
    mov [esp-4], ebx
    jg short L2
    jl short L1
    xor eax, eax
    ret 0
L1:
    neg ecx
L2:
    xor ebx, ebx
L3:
    mov eax, -858993459
    mul ecx
    mov eax, edx
    shr eax, 3
    mov edx, ecx
    lea ecx, [eax+eax*4]
    add ecx, ecx
    sub edx, ecx
    add ebx, edx
    mov ecx, eax
    cmp ebx, 9
    jbe short L4
    sub ebx, 9
L4:
    test eax, eax
    jnz short L3
    mov eax, ebx
    mov ebx, [esp-4]
    ret 0
  }
}

EXEMPLE UTILISATION:

void __stdcall OnNbr(HWND hdlg)
{
  int n, bok;
  char szres[4];
  n = GetDlgItemInt(hdlg, IDED_INT, &bok, 1);
  if(!bok) MessageBox(hdlg, "ERREUR", "SumInt", 0x30);
  szres[0] = bnsumint(n) + 48;
  szres[1] = 0;
  SetDlgItemText(hdlg, IDST_SUM, szres);
}
Langage : VB6
Date ajout : 18/05/2007
Posté par Gobillot [Liste]
' marche avec tout type de numérique:
'   Byte, Integer, Long, Double, Décimal, (chaîne mais avec restriction)
Private Function SommeChiffre(nombre As Variant) As Long
    Dim n As Variant, t As Variant, s As Long
    n = Int(nombre)
    While n > 0
          t = n
          n = Int(t / 10)
          s = s + t - n * 10
          Wend
    SommeChiffre = s
End Function

Langage : C
Date ajout : 18/05/2007
Posté par vicenzo [Liste]
resultat compris entre 0 et 9
-/+ integer 

int intsum(int num)
{
    int n = 0, i = abs(num);
 
    while (i) { n += i%10; i /= 10; }
 
    return ( (n >= 10) ? intsum(n) : n);
}
Langage : Delphi 5
Date ajout : 20/05/2007
Posté par japee [Liste]
function SumOfDigits(Number: Int64): Integer;
var Tmp: Extended;
begin
  Number := Abs(Number);
  Result := 0;
  while Number <> 0 do
  begin
    Tmp := Number / 10;
    Inc(Result, Round(Frac(Tmp) * 10));
    Number := Trunc(Tmp);
  end;
end;
Remarque :
Limite du paramètre d'entrée : étendue du Int64 (64 bits, signé).
Langage : Delphi 5
Date ajout : 25/05/2007
Posté par f0xi [Liste]
function SelfSum(const V : int64) : integer; overload;
var N : int64;
begin
  N := abs(V);
  result := 0;
  while N > 0 do
  begin
    result := result + (N mod 10);
    N := N div 10;
  end;
end;

function SelfSum(const V : extended) : integer; overload;
var S : string;
    L,N : integer;
const
  CTN : array['0'..'9'] of byte = (0,1,2,3,4,5,6,7,8,9);
begin
  S      := FloatToStrF(V,ffFixed,20,22);
  result := 0;
  N      := 1;
  L      := Length(S);
  while N <= L do
  begin
    if S[N] in ['0'..'9'] then
    begin
      result := result + CTN[ S[N] ];
    end;
    N := N+1;
  end;
end;
Langage : ObjectiveCaml
Date ajout : 02/06/2007
Posté par Cacophrene [Liste]
(* Fonction récursive terminale. Exemple d'utilisation : sum 12345 = 15 *)
let sum n =
    let rec loop total = function
        | 0 -> total
        | n -> loop (total + n mod 10) (n / 10)
    in loop 0 n

Langage : ActionScript Flash
Date ajout : 12/06/2007
Posté par faiblard [Liste]
var iNombre:Number = 0;
var iSomme:Number = 0;
function fSommeDesNombre (iNombre)
{
	if (iNombre > 0)
	{
		while (int (iNombre) > 0)
		{
			iSomme += Math.floor (iNombre) % 10;
			iNombre /= 10;
		}
	}
	else
	{
		while (int (iNombre) < 0)
		{
			iSomme += Math.ceil (iNombre) % 10;
			iNombre /= 10;
		}
	}
	return iSomme;
}

Remarque :
Marche pour les nombres négatifs et positifs
Langage : PHP 3 , PHP 4 , PHP 5
Date ajout : 12/06/2007
Posté par coucou747 [Liste]
<?php
$a=10455;
$s=0;
while ($a!=0){
   $s+=$a%10;
   $a=intval($a/10);
}
print $s;
?>
Langage : Perl
Date ajout : 12/06/2007
Posté par coucou747 [Liste]
$a=10455;
$s=0;
while ($a!=0){
   $s+=$a%10;
   $a=int($a/10);
}
print $s;

Langage : VB6 , VBA
Date ajout : 09/11/2007
Posté par jrivet [Liste]
DateMAJ : 09/11/2007
Option Explicit
Private Sub Form_Load()
   MsgBox SommeChiffre(1234)
   MsgBox SommeChiffre("1234")
   MsgBox SommeChiffre("12test34")
End Sub 
' marche avec tout type de numérique: '   Byte, Integer, Long, Double, Décimal, (chaîne mais avec restriction) Private Function SommeChiffre(nombre As Variant) As Long Dim N As String Dim i As Integer    N = nombre    'On place une gestion d'erreur si caractere    On Error Resume Next    For i = 1 To Len(N)        SommeChiffre = SommeChiffre + CInt(Mid(N, i, 1))    Next    On Error GoTo 0 End Function
Remarque :
Autres variante en VB6
Langage : VB 2005
Date ajout : 09/11/2007
Posté par jrivet [Liste]
DateMAJ : 09/11/2007
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       MessageBox.Show (SommeChiffre(1234))
       MessageBox.Show (SommeChiffre("1234"))
       MessageBox.Show (SommeChiffre("12test34"))
   End Sub 
   ' marche avec tout type de numérique:    '   Byte, Integer, Long, Double, Décimal, (chaîne mais avec restriction)    Private Function SommeChiffre(ByVal nombre As Object) As Long        Dim Result As Long        Dim tmp As Long        'On place une gestion d'erreur si caractere        Try            Dim N As String = nombre.ToString            For i As Integer = 0 To N.Length - 1                If Long.TryParse(N.Substring(i, 1), tmp) Then                    Result += tmp                End If            Next        Catch ex As Exception            Result = -1        End Try        Return Result    End Function
Remarque :
Une proposition en VB2005. Ne connaissant que très peu les innombrables possibilité de .NET 2005 je propose celle ci, mais je suis à peu près sûr qu'il y a plus simple et plus rapide. A vous d'éclairer ma lanterne.
@+

Snippets en rapport avec : Calcul, Chiffre, Nombre, Somme



Codes sources en rapport avec : Calcul, Chiffre, Nombre, Somme

{JAVA / J2EE} ADDITION DE DEUX NOMBRES RÉELS "COMME A LA MATERNELLE"
Le programme prend deux réels positifs en arguments et les additionne, en faisant l'operation sur le...

{Visual Basic, VB6, VB.NET, VB 2005} CHIFFRE EN LETTRE FONCTION
Une petite fonction simlpe pour transformer un chiffre en lettre. Exemple: "15193" >> dix ...

{Delphi} CONVERSION LITTÉRALE D'UN NOMBRE ENTIER OU FLOTTANT
Affiche en toutes lettres un nombre avec ou sans virgule, avec son unité (monétaire, mesure, etc...)...

{Javascript / DHTML} FORMATER UN NOMBRE, FAÇON NUMBER FORMAT DE PHP
Formate un nombre pour l'affichage (retourne une chaîne représentant un nombre formaté) Permet de c...

{PHP} NOMBRE_PREMIER
Un petit programme qui liste des nombres premiers jusqu'a $limit limite...

{Visual Basic, VB6, VB.NET, VB 2005} UN PETIT PROGRAMME DE CALCUL DES NOMBRE PREMIERS
qu'on vous appuiez sur calculer il va mettre les nombre dans un fichier texte dans C: appeler premie...

{Visual Basic, VB6, VB.NET, VB 2005} CONVERTIR DES CHIFFRES EN LETTRES AVEC OU SANS DÉCIMALE ET/OU MONÉTAIRE
je sais qu'il en existe déjà plusieurs mais celui-ci n'utilise qu'une boucle de traitement (centai...

{Visual Basic, VB6, VB.NET, VB 2005} BIGMATH - OPERATIONS SUR DES TRES GRANDS NOMBRES
ajoute ce module dans ton projet et tu pourra utiliser les fonctions suivantes sur des nombres conte...

{Python} NOMBRE MYSTERE
Bon c'est un programme qui genere un nombre aleatoire. Ok c'est basique mais c'est tres commenter do...

{Visual Basic, VB6, VB.NET, VB 2005} ECRIRE DES NOMBRES EN TOUTES LETTRES (MULTI-LANGUAGE)
ce code permet de transformer un nombre (double) en son interpretation en toutes lettres (string). ...