- 1
Write a c++ program that generates armstrong numbers upto a limit n.
c++ program that generates armstrong numbers upto a limit n
2 Réponses
+ 1
Please try this
/*********************************************************
Print all armstrong numbers between given range
find the no of digits
find the sum of power of digits of each digit in the num
compare the sum with original value
*********************************************************/
#include <iostream>
#include <math.h>
using namespace std;
//Function that returns the no of digits in the number
long DigitCount(long x){
long c=0;
do{
x = x / 10;
c++;
}while (x != 0);
return c;
}
//Function returns the sum of digit raised to the power c
long SumofDigits (long num, long p){
long r, s = 0;
do{
r = num % 10;
s = s + pow(r,p) ;
num = num / 10;
}while (x != 0);
return s;
}
int main (void ){
long curr, res, start, end;
cout<<"Enter start number: "; cin>>start;
cout<<"Enter end number: ";cin>>end;
if (start > end) { //perform swapping if the start value is bigger than end value
int temp;
temp = start;
start = end;
end = temp
}
for (curr=start;curr<=end;curr++){
res = SumofDigits(curr,DigitCount(curr));
if (res==curr) cout<<curr<<" ";
}
}
0
#include <stdio.h>
#include <conio.h>
int getCubicSumOfDigits(int number);
int main(){
int number, sum, counter;
printf("Enter a number : ");
scanf("%d", &number);
printf("Armstrong numbers between 0 and %d\n", number);
/* Iterate from 0 till N, and check for Armstrong number */
for(counter = 0; counter <= number; counter++){
sum = getCubicSumOfDigits(counter);
if(sum == counter){
printf("%d\n", counter);
}
}
getch();
return 0;
}
/*
* Funtion to calculate the sum of cubes of digits of a number
* getCubicSumOfDigits(123) = 1*1*1 + 2*2*2 + 3*3*3;
*/
int getCubicSumOfDigits(int number){
int lastDigit, sum = 0;
while(number != 0){
lastDigit = number%10;
sum = sum + lastDigit*lastDigit*lastDigit;
number = number/10;
}
return sum;
}
Source : http://www.techcrashcourse.com/2014/10/c-program-generate-armstrong-numbers.html
http://www.techcrashcourse.com/2017/01/cpp-program-print-armstrong-number-between-given-interval.html