Divisors

I have to write a program which displays how many divisors containing the digit "3" does the number entered have. When I introduce a number, nothing happens.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>

using namespace std;

int main()
{
    int n, d=1, nr=0, x;
    cin>>n;
    while(d<=n)
    {
        int OK=0;
        if(n%d==0)
        {
            while(d!=0)
            {
                x=d%10;
                d=d/10;
                if(x==3)
                {
                    OK=1;
                }
            }
        }
        if(OK==1) {nr++;}
        d++;
    }
    cout<<nr;
    return 0;
}
The problem is the inner loop where you modify d so the it will never reach n. What is this inner loop good for?

[EDIT]
Copy d into another temporary variable which you can modify place of d in the inner loop.
Last edited on
I've tried to rn, but it still doesn't work. I'm doing something wrong lol. Mind telling me how would you do it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

using namespace std;

int main()
{
    int n, d=1, nr=0, x;
    cout << "Input a number: ";  // so we know what's expected
    cin>>n;
    while(d<=n)
    {
        int OK = 0;
        if(n%d==0)             // so d is a divisor; now, does it have a 3 in ...
        {
            int divisor = d;   // do what coder777 suggested ... 
            while(divisor!=0)  // ...
            {
                x=divisor%10;  // the particular digit
                divisor/=10;   // ...
                if(x==3)
                {
                    OK=1;
                }
            }
        }
        if(OK==1) nr++;
        d++;
    }
    cout<<nr;
    return 0;
}


Input a number: 90
2
Last edited on
Just playing with it... alternative approach
1
2
3
4
5
6
7
8
9
char dtxt[100];
char * has3;
...
int divisor = d;   // do what coder777 suggested ... 
sprintf(dtxt,"%i",d) 
has3 = strstr(dtxt,"3");
  
if (has3)
 cout << dtxt << endl;


Last edited on
Topic archived. No new replies allowed.