Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
`\#include \<bits/stdc++.h\>
using namespace std;
int main(){
int N;
cin \>\> N;
int sum = 0;

vector\<int\> a(N);

int A, B;
cin \>\> A \>\> B;

for (int i = 0; i \< N; i++) {
a\[i\] = i + 1;
int num = a\[i\];
int digitsum = 0;

     if((a[i] >= A) && (a[i] <= B)) {
        sum = sum + a[i];
    } else if (a[i] > 0) {
        while (a[i] > 0) {
            digitsum += a[i] % 10;
            a[i] = a[i] / 10;
        }
        if (digitsum >= A && digitsum <= B) {
            sum = sum + num;
        }
    }

}

cout \<\< sum \<\< endl;
}

`


What I have tried:

for eg N=100 A=4 B=16
outpt should be 4554 but coming 4587
Posted
Updated 25-Jul-23 23:48pm
Comments
Member 15627495 26-Jul-23 4:49am    
add few 'cout' , in the aim of reading the values in your var.

it's a part of debuging "vars tracing".

organize few test with different values for A and B.
Richard MacCutchan 26-Jul-23 5:01am    
What are the rules for converting the input numbers to the output answer?

Assuming I understand what the code is supposed to do, I would start by simplify the code:
C++
<pre>`\#include \<bits/stdc++.h\>
using namespace std;
int main(){
int N;
cin \>\> N;
int sum = 0;

vector\<int\> a(N);

int A, B;
cin \>\> A \>\> B;

for (int i = 0; i \< N; i++) {
a\[i\] = i + 1;
int num = a\[i\];
int digitsum = 0;

     if((a[i] >= A) && (a[i] <= B)) {
        sum = sum + a[i];
    } else if (a[i] > 0) {
        while (a[i] > 0) {
            digitsum += a[i] % 10;
            a[i] = a[i] / 10;
        }
        if (digitsum >= A && digitsum <= B) {
            sum = sum + num;
        }
    }

}

cout \<\< sum \<\< endl;
}

`

12 is not the sum of its digits.
 
Share this answer
 
v2
Comments
awesome priyanshu 28-Jul-23 1:50am    
can you explain me with an example
Patrice T 28-Jul-23 4:24am    
Read last line in solution !
as per your code 10, 11, 12 are added as 10, 11 and 12, but sum of digits are 1, 2 and 3 which are out of range.
Based on Patrice solution, I would simplify further:
C++
#include <iostream>
  
using namespace std;
int main()
{
  int N;
  int A, B;
  cin >> N;
  cin >> A >> B;

  int sum = 0;
  for (int i = 1; i <= N; ++i)
  {

    int num = i, digitsum = 0;
    while (num > 0)
    {
        digitsum += num % 10;
        num /= 10;
    }
    if (digitsum >= A && digitsum <= B)
    {
        sum += i;
    }
  }
  cout << sum << endl;
}
 
Share this answer
 
v2
Comments
Patrice T 26-Jul-23 6:46am    
+5
CPallini 26-Jul-23 6:49am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900