C++ Problem Sequence

Question: Generate 10 terms of sequence like 1, 2, 4, 8, 16, 22, 26,
38, 62, 74, 102, 104, ...
1
2
3
4
5
6
7
8
9
10
11
12
int x = 1,num,num1,n = 1;
    while( n <= 10){
          if(n==1){
          cout<<x<<", ";
          }
          num = x%10;
          num1 = num%10;
                    x = x + (num * num1);
          cout<<x<<", ";
          n++;

    }

What's wrong in my code? I am confused.
Logic is
2 = 1 + (1*1)
4 = 2 + (2*1)
8 = 4 + (4*1)
16 = 8 + (8*1)
22 = 16 + (1*6)
Last edited on
a(1) = 1; a(n+1) = a(n) + product of nonzero digits of a(n).
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int prod( int n ) { return n < 10 ? n : prod( n / 10 ) * ( n % 10 ); }

int main()
{
   int N = 10, a = 1;   cout << a << ' ';
   while( --N ) cout << ( a += prod( a ) ) << ' ';
}



talal02 wrote:
What's wrong in my code?

(1) You haven't given enough of it to compile.
(2) @cool123dude gives an infinitely better explanation of the logic (and is what I coded off).
(3) You presume that your numbers are two digits.
(4) You calculate those digits incorrectly; even if numbers were only 2 digits (which isn't many of them) then the first digit would be x / 10 and the second would be x % 10 ... but most won't be 2 digits anyway, so this won't work very well.
Last edited on
Topic archived. No new replies allowed.