Write a program in visual studio C++ 2008 If you add up all the digits in 468, y
ID: 3625594 • Letter: W
Question
Write a program in visual studio C++ 2008If you add up all the digits in 468, you get 4+6+8=18. The square and cube of 468 are
219024 and 102503232, respectively. Interestingly, if you add up the digits of the square or cube, you
get 18 again. Are there other integers that share this property? Write a program that lists all positive
integers k less than 1000 such that k, k2, and k3 have digits that add up to the same number.
create variables to represent strings, array of strings,2 nested loops,need to copy 1 element at a time,use of atoi and itoa, can use division and mod, use cstring manipulation, convert int to string, convert char back to int .
pseudocode
for n = 1 to 1000 {
// nsquared = n * n;
// ncubed = n * n * n;
// convert n to string array (atoi)
// convert nsquared to string array (atoi)
// convert ncubed to sting array (atoi)
// sumofdigits = 0;
// for each digit in n's array {
// copy digit to array of size 2 with second character being ''
// convert digit array to integer
// add integer to sumofdigits
theres another separate loop for nsquared and ncubed
//if(sumofdigits == sumofnsdigits == sumofncdigits) {
// print n
example to help with program -------------------
include<cstring>
include<cstdlib>
using namespace std;
int main(){
char demo[5];
char digit[2];
digit[1]= '';
int n = 500;
itoa (500, demo + 1,10); //+1 is for 2nd character output
strncpy (digit, demo, 1);int n = atoi(digit);
cout<<demo<<endl;
need to copy one element at a time
strncpy-number of characterd to copy into a string
Explanation / Answer
// dude your pesudo code seems to be a bit complex
// we can implement with simple logic by using long data type.
// your code goes below.....go ahead.
#include<iostream.h>
#include<cstring>
#include<cstdlib>
using namespace std;
int sumofdigits(long k)
{
int rem, sum=0;
while(k!=0)
{
rem=k%10;
sum+=rem;
k/=10;
}
return sum;
}
int main()
{
int sum=0;
int sumsquare=0;
int sumcube=0;
for(long n=1; n<1000; n++)
{
sum = sumofdigits(n);
sumsquare = sumofdigits(n*n);
if(sum==sumsquare)
{
sumcube = sumofdigits(n*n*n);
if(sum==sumcube)
cout << "Found Number :" << n <<endl;
}
}
system("pause");
return 0;
}
OUTPUT:
Found Number :1
Found Number :10
Found Number :100
Found Number :468
Found Number :585
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.