From 89bfc1244e658ebe4e1b09ba6800815b4f103f36 Mon Sep 17 00:00:00 2001 From: Harsh Tripathi <63543719+happy-t@users.noreply.github.com> Date: Wed, 13 Oct 2021 09:19:09 -0700 Subject: [PATCH] fix: Armstrong number bug fixes (#1689) * added a new directory named Recursion and a most common exxample of recusion i.e. Tower of Hanoi in it * Added Comments * Bug fixed according to the correct definition of armstrong_number * Bug Fixed in armstrong_number.cpp Bug Fixed in armstrong_number.cpp according to the correct definition of armstrong_number. * Update armstrong_number.cpp * Added documentation * Delete Recursion directory * Update armstrong_number.cpp * Update dynamic_programming/armstrong_number.cpp Co-authored-by: David Leal * Update armstrong_number.cpp fixed errors. * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review * Update armstrong_number.cpp Applied suggested changes. * Update armstrong_number.cpp Co-authored-by: David Leal --- dynamic_programming/armstrong_number.cpp | 44 +++++++++++++++++------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp index 270a705f7..ba8f054dd 100644 --- a/dynamic_programming/armstrong_number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -1,21 +1,41 @@ // Program to check whether a number is an armstrong number or not #include - +#include using std::cin; using std::cout; int main() { - int n, k, d, s = 0; - cout << "Enter a number:"; + int n = 0, temp = 0, rem = 0, count = 0, sum = 0; + cout << "Enter a number: "; cin >> n; - k = n; - while (k != 0) { - d = k % 10; - s += d * d * d; - k /= 10; + + temp = n; + + /* First Count the number of digits + in the given number */ + while(temp != 0) { + temp /= 10; + count++; } - if (s == n) - cout << n << "is an armstrong number"; - else - cout << n << "is not an armstrong number"; + + /* Calaculation for checking of armstrongs number i.e. + in a n digit number sum of the digits raised to a power of n + is equal to the original number */ + + temp = n; + while(temp!=0) { + rem = temp%10; + sum += (int) pow(rem,count); + temp/=10; + } + + + if (sum == n) { + cout << n << " is an armstrong number"; + } + else { + cout << n << " is not an armstrong number"; + } + + return 0; }