How to subtract smallest element from sum of array elements - c++

For each test case t, I need to input n, the number of elements in an array, and input those elements. Then I have to subtract the smallest element in the array from the sum of all the other elements. Here is my code, but I keep getting TLE:
#include <bits/stdc++.h>
int main(void) {
int t;
std::cin >> t;
while (t --) {
int n, sum = 0, a, k = 100000;
std::cin >> n;
while (n --) {
std::cin >> a;
if (a < k) {
k = a;
} else {
sum += a;
}
n --;
}
std::cout << abs(sum - k) << "\n";
}
}
Sample Input:
3
5
20 16 8 2 13
6
16 9 12 20 15 14
4
2 2 2 2
Sample Output:
55
68
4

In this if statement
if (a < k) {
you are comparing each entered value with the current value of k and if it is less than k you are not adding it to sum.
For example for this sequence of numbers
20 16 8 2 13
20 is less than the initial value of k. So now k is equal to 20 and the number is not added to sum.. The next number 16 is also less than the current value of k. And again it is not added to sum.
You need to sum all numbers and at the same time find the minimum number. And then after the loop subtract the minimal number from sum.
Also this statement
n --;
is redundant.
The program can look the following way
#include <iostream>
int main()
{
unsigned int t = 0;
std::cin >> t;
while ( t-- )
{
unsigned int n = 0;
long long int sum = 0;
int min = 0;
bool first = true;
std::cin >> n;
while ( n-- )
{
int x;
std::cin >> x;
if ( first || x < min )
{
first = false;
min = x;
}
sum += x;
}
std::cout << ( sum < min ? min - sum : sum - min ) << '\n';
}
return 0;
}
For the input
1
5
20 16 8 2 13
the program output is
57

Related

Task done right, answer not being accepted

I am having issues with a task I've done, it outputs answer correctly without any errors. It gives me 2/3 points, last shows error, and doesn't show what. I've no clue what I've done wrong. Can someone have a look at this please.
Task:
A perfect number is a natural number that is equal to the sum of all its natural divisors (different from itself).
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
A redundant number is a natural number which is greater than the sum of all its natural divisors (different from itself).
9> 1 + 3
The deficit number is a natural number that is less than the sum of all its natural divisors (different from itself).
12 <1 + 2 + 3 + 4 + 6
Input
A natural number N (N <1000) followed by N natural numbers (not greater than 32000).
Remember 0 is an natural number.
For each of the numbers given in the input, the program should print a line of the form on the screen:
X - perfect / redundant / deficit number
depending on the type of number.
Sample input
6 15 28 6 56 22 496
Sample output
15 - redundant number
28 - perfect number
6 - perfect number
56 - deficit number
22 - redundant number
496 - a perfect number
#include <iostream>
using namespace std;
void ifPerfect(int n)
{
int sum = 0;
for (int i = 1; i <= n / 2; i++)
if (n % i == 0)
sum += i;
if (sum == n)
{
cout << n << " - perfect number" << endl;
}
}
void ifRedundant(int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (n > sum)
{
cout << n << " - redundant number" << endl;
}
}
void ifDeficit(int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (n < sum)
{
cout << n << " - deficit number" << endl;
}
}
int main()
{
int n;
cin >> n;
if (n >= 0 && n < 1000)
{
int *tab = new int[n];
for (int i = 0; i < n; i++)
{
cin >> tab[i];
}
for (int i = 0; i < n; i++)
{
ifRedundant(tab[i]);
ifPerfect(tab[i]);
ifDeficit(tab[i]);
}
delete[] tab;
return 0;
}
}
According to Wiki (https://en.wikipedia.org/wiki/Perfect_number), 0 is NOT a perfect number, while your program would say that it is.
Given an input of 0, you program will produce an incorrect answer.
The clue was the statement "Remember 0 is an natural number."
While natural, it is not perfect.

Private test cases are not passing. What is the mistake here? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Given N three-digit numbers, your task is to find bit score of all N numbers and then print the number of pairs possible based on these calculated bit score.
Rule for calculating bit score from three digit number:
From the 3-digit number,
· extract largest digit and multiply by 11 then
· extract smallest digit multiply by 7 then
· add both the result for getting bit pairs.
Note: - Bit score should be of 2-digits, if above results in a 3-digit bit score, simply ignore most significant digit.
Consider following examples:
Say, number is 286
Largest digit is 8 and smallest digit is 2
So, 8*11+2*7 =102 so ignore most significant bit , So bit score = 02.
Say, Number is 123
Largest digit is 3 and smallest digit is 1
So, 3*11+7*1=40, so bit score is 40.
Rules for making pairs from above calculated bit scores
Condition for making pairs are
· Both bit scores should be in either odd position or even position to be eligible to form a pair.
· Pairs can be only made if most significant digit are same and at most two pair can be made for a given significant digit.
Constraints
N<=500
Input Format
First line contains an integer N, denoting the count of numbers.
Second line contains N 3-digit integers delimited by space
Output
One integer value denoting the number of bit pairs.
Test Case
Explanation
Example 1
Input
8 234 567 321 345 123 110 767 111
Output
3
Explanation
After getting the most and least significant digits of the numbers and applying the formula given in Rule 1 we get the bit scores of the numbers as:
58 12 40 76 40 11 19 18
No. of pair possible are 3:
40 appears twice at odd-indices 3 and 5 respectively. Hence, this is one pair.
12, 11, 18 are at even-indices. Hence, two pairs are possible from these three-bit scores.
Hence total pairs possible is 3
#include <iostream>
#include <vector>
using namespace std;
vector<int> correctBitScores(vector<int>);
vector<int> bitScore(vector<int>);
int findPairs(vector<int>);
int main() {
int a, b;
int pairs = 0;
vector<int> vec;
vector<int> bitscore;
cout << "\nEnter count of nos: ";
cin >> a;
for (int i = 0; i < a; i++) {
cin >> b;
vec.push_back(b);
}
bitscore = bitScore(vec);
pairs = findPairs(bitscore);
cout << "Max pairs = " << pairs;
return 0;
}
vector<int> correctBitScores(vector<int> bis) {
int temp = 0;
for (size_t i = 0; i < bis.size(); i++) {
temp = bis[i];
int count = 0;
while (temp > 0) {
temp = temp / 10;
count++;
}
if (count > 2)
bis[i] = abs(100 - bis[i]);
}
/*cout << "\nCorrected" << endl;
for (int i = 0; i < size(bis); i++) {
cout << bis[i] << endl;
}*/
return bis;
}
int findPairs(vector<int> vec) {
int count = 0;
vector<int> odd;
vector<int> even;
for (size_t i = 0; i < vec.size(); i++)
(i % 2 == 0 ? even.push_back(vec[i]) : odd.push_back(vec[i]));
for (size_t j = 0; j < odd.size(); j++)
for (size_t k = j + 1; k < odd.size(); k++) {
if (odd[j] / 10 == odd[k] / 10) {
count++;
odd.erase(odd.begin()+j);
}
}
for (size_t j = 0; j < even.size(); j++)
for (size_t k = j + 1; k < even.size(); k++) {
if (even[j] / 10 == even[k] / 10) {
count++;
even.erase(even.begin() + j);
}
}
return count;
}
vector<int> bitScore(vector<int> v) {
int temp = 0, rem = 0;
vector<int> bs;
for (size_t i = 0; i < v.size(); i++) {
int max = 0, min = 9;
temp = v[i];
while (temp > 0) {
rem = temp % 10;
if (min > rem)
min = rem;
if (max < rem)
max = rem;
temp = temp / 10;
}
int bscore = (max * 11) + (min * 7);
bs.push_back(bscore);
}
/*cout << "\nBit Scores = " << endl;
for (int i = 0; i < size(bs); i++) {
cout << bs[i] << endl;
}*/
bs = correctBitScores(bs);
return bs;
}
I tried doing it very simple c++ code as per my understanding of Que,can you just verify it more test cases.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,count=0;
cin>>n;
vector<int>v(n);
for(int i=0;i<n;i++){
cin>>v[i];
string s = to_string(v[i]);
sort(s.begin(),s.end());
int temp = (s[s.length()-1]-'0')*11 + (s[0] - '0')*7;
v[i] = temp%100;
}
unordered_map<int ,vector<int>>o,e;
for(int i=0;i<n;i=i+2){
o[v[i]/10].push_back(i+1);
}
for(int i=1;i<n;i=i+2){
e[v[i]/10].push_back(i+1);
}
count=0;
for(int i=0;i<10;i++){
int os=o[i].size(),es=e[i].size();
if(os==2)
count++;
if(es == 2)
count++;
if(os>2 || es>2)
count += 2;
}
cout<<count;
}

Functions problem displaying the output and intput

I need to write a program that will get 2 integers. The program will then display the
following:
a. The sum of all integers that are both divisible by 4 and 6 between the two numbers inputted.
b. The average of all integers both divisible by 3 and 7 between the two numbers inputted.
I tried doing the code down below:
#include <iostream>
using namespace std;
int Sum46(int a, int b)
{
int sum = 0;
for (int i = a; i <= b; i++) {
if (i % 4 == 0 && i % 6 == 0) {
sum = sum + i;
}
}
return sum;
}
int Sum37(int j, int k)
{
int sum1 = 0;
for (int i = j; i <= k; i++) {
if (i % 3 == 0 && i % 7 == 0) {
sum1 = sum1 + i;
}
}
return sum1;
}
int Count(int f, int g)
{
int inputCount = 0;
for (int i = f; i < g; i++) {
if (i % 3 == 0 && i % 7 == 0) {
inputCount++;
}
}
return inputCount;
}
int Ave(int t, int u)
{
int total = 0;
total = t / u;
return total;
}
void display(int o, int l)
{
cout << "The sum of all integers that are both divisible by 4 and 6 between two numbers is " << o << endl;
cout << "The sum of all integers that are both divisible by 3 and 7 between two numbers is " << l << endl;
}
int main()
{
int num1, num2;
int probA, probB, comp, bilang;
cout << "Input first number : ";
cin >> num1;
cout << "Input second number : ";
cin >> num2;
probA = Sum46(num1, num2);
comp = Sum37(num1, num2);
bilang = Count(num1, num2);
probB = Ave(comp, bilang);
display(probA, probB);
return 0;
}
My expected result should be
Input first number : 4
Input second number : 12
The sum of all integers that are both divisible by 4 and 6 between two numbers is 12
The sum of all integers that are both divisible by 3 and 7 between two numbers is 0
"since 12 is the only number that is both divisible by 4 and 6 and no number is divisible by 3 and 7 on the inputted numbers."
But the actual results are
Input first number : 4
Input second number : 12
"That is the only result and I was not able to produce any output of the functions"
You have to check for the case where u is 0.
Change this:
int Ave(int t, int u)
{
int total = 0;
total = t / u;
return total;
}
To this:
int Ave(int t, int u)
{
if( u == 0 )
return -1;
return t/u;
}

Count occurences of each digit in integer interval (or int array)

using loops, how to find occurences of each digit in integer interval [n, m]?
for example:
INPUT n,m = [19, 23] = 19, 20, 21, 22, 23
OUTPUT should be:
0 occurences: 1 times
1 occurences: 2 times
2 occurences: 5 times
3 occurences: 1 times etc.
#include <iostream>
using namespace std;
int main()
{
int i, j, z, count, n, m;
cin >>n >>m;
for(int i=0; i<10; i++) // LOOP FOR DIGITS
{
cout << i <<"occurences: ";
count=0;
for(int j=n; j<m; j++) // LOOP INTEGER INTERVAL
{
while (z!=0)
{
z = j % 10; // LAST DIGIT OF FIRST NUMBER IN INTERVAL
if (z == i) count++;
z /= 10;
}
}
cout << count <<" times"<< endl;
}
}
my code returns 0 times for each digit, where is the error?
You don't need to loop over the range 10 times.
int n, m;
cin >> n >> m;
counts = int[10];
for(int i = 0; i < 10; ++i) {
counts[i] = 0;
}
for(int j = n; j <= m; j++) {
int z = j;
do {
int digit = z % 10; // LAST DIGIT OF FIRST NUMBER IN INTERVAL
counts[digit]++;
z /= 10;
} while (z != 0);
}
for(int i = 0; i < 10; ++i) {
cout << i << " occurrences " << counts[i] << " times";
}
You can use std::stringstream to get each digit in a number like so:
constexpr int n = 19;
constexpr int m = 23;
std::array<int, 10> digit_count = {0};
for (int i = n; i <= m; i++)
{
std::stringstream s;
s << i;
unsigned char digit;
while (s >> digit) digit_count[digit - '0']++;
}
Some issues that I see:
z = j % 10;
You need to intialize z outside your while loop to j Also you want to get the mod but not set z to it. try putting the result into a temp variable as opposed to into z.
Your for loop is not inclusive of the last number. for(int j=n; j<m; j++) should be j<=m.
z = j;
while (z!=0)
{
int mod = z % 10; // LAST DIGIT OF FIRST NUMBER IN INTERVAL
if (mod == i) count++;
z /= 10;
}
}
This final code gives the correct result:
#include <iostream>
using namespace std;
int main()
{
int i, j, z, count, n, m;
cin >>n >>m;
for(int i=0; i<10; i++) // LOOP FOR DIGITS
{
cout << i <<" occurences: ";
count=0;
for(int j=n; j<=m; j++) // LOOP INTEGER INTERVAL
{
z = j;
while (z!=0)
{
int mod = z % 10; // LAST DIGIT OF FIRST NUMBER IN INTERVAL
if (mod == i) count++;
z /= 10;
}
}
cout << count <<" times"<< endl;
}
}
19 23
0 occurences: 1 times
1 occurences: 2 times
2 occurences: 5 times
3 occurences: 1 times
4 occurences: 0 times
5 occurences: 0 times
6 occurences: 0 times
7 occurences: 0 times
8 occurences: 0 times
9 occurences: 1 times
Basically, the modulo operation is used to retrieve the least significant digit of any number. Dividing this number with the radix will remove the least significant digit, making the next digit the new least significant digit.
int main(int argc, char *argv[])
{
int radix = 10;
int x, y;
printf("Lower bound: ");
scanf("%d, &x);
printf("Upper bound: ");
scanf("%d, &y);
int digits[radix];
count_digit_occurence(x, y, radix, digits);
int i;
for (i = 0; i < radix; ++i)
{
int occ = digits[i];
printf("%d occurred %d times\n", i, occ);
}
}
void count_digit_occurence(int x, int y, int radix, int digits[radix])
{
int i, n;
for (i = x; i <= y; ++i)
{
n = i;
while (n > 0)
{
++(digits[n % radix]);
n /= radix;
}
}
}
All the answers so far provide algorithms with complexity O(m-n) at best, i.e. linear in the distance from n to m. Here, I provide a method that has logarithmic complexity. The basic idea is to consider the last digit of each number first, then the second last etc.
In order to simplify the code, I change the problem slightly and consider the range [n, m-1], i.e. excluding m.
There are m-n numbers in this range; if this is is a multiple of 10, then each last digit occurs exactly (m-n)/10 times. Otherwise, we must account for the edges. The following routine adds to count unit times the number of occurrences of the last digits in all numbers in the range from n to m-1 inclusive.
void count_last_digits(int n, int m, std::array<int,10> count&, int unit=1)
{
// 1 increment n until it has the same last digit as m
for(int dn=n%10, dm=m%10; n<m && dn!=dm; dn=++n%10)
count[dn] += unit;
// 2 add unit*(m-n)/10 to all counts
if(int cnt = unit*(m-n)/10) // avoid to add nothing
for(int d=0; d!=10; ++d)
count[d] += cnt;
}
Once, we counted the last digits, we count the second last digits etc. First, we need a helper function that just counts the digits of a single number
void count_digits(int x, std::array<int,10> &count, int unit=1)
{
for(; x; x/=10)
count[x%10] += unit;
}
To proceed with the second last digits, we first trim (using this helper function) the interval such that both n and m are multiples of 10, then divide them both by 10, multiply the unit of counting by 10, and recurse
std::array<int,10> count_all_digits(int n, int m)
{
std::array<int,10> count={0};
for(int unit=1; n<m; n/=10,m/=10,unit*=10) {
// count last digits
count_last_digits(n, m, count, unit);
// increment n to the next multiple of 10, but not above m
if(int inc = std::min(10-(n%10), m-n)) {
count_digits(n/10, count, unit*inc);
n += inc;
}
// decrement m to the previous multiple of 10, but not below n
if(int dec = std::min(m%10, m-n)) {
count_digits(m/10, count, unit*dec);
m -= dec; // not really necessary
}
}
return count;
}
The functions count_last_digits() and count_digits() have complexity O(1) and O(ln(x)), respectively. Both are called O(ln(m)) times, so the latter dominates the overall complexity, which is O(ln(m)^2).
Note that these functions assume 0 < n <= m, i.e. n<=0 is not allowed.

Finding how many a specific digit appears in array of numbers (C++)

I'm doing an online challenge and the challenge is the following:
"Kids are playing a game called "Counting digits". For given numbers S and K, they firstly write all numbers between those numbers and then count how many times each digit appears (0,1,2,3,4,5,6,7,8,9). For example, S=767, K=772, numbers will be: 767,768,769,770,771,772
So, 0 will show once (in 770), 1 will show once (in 771) and so on..
Basically, my program have to do the following (given example):
Input:
1 9
(These are numbers 1,2,3,4,5,6,7,8,9)
Output:
0 1 1 1 1 1 1 1 1 1
(0 doesn't show, other numbers show once)."
I'm stuck on this code... out of ideas.
#include <iostream>
using namespace std;
int main()
{
int s,k;
int array[10];
int c0=0,c1=0,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
cin >> s >> k;
int saves = s;
int savek = k;
cout << s%10;
for(int i=s;i<=k;i++)
{
int savei=i;
while(savei!=0)
{
savei=savei%10;
}
}
Any pseudo code/snippet/code/hint is appreciated.
Purely numeric solution to a purely numeric problem:
#include <iostream>
int main()
{
int s, k, i, tmp;
std::cin >> s >> k;
int count[10] = { 0 };
for (i = s; i <= k; i++) {
tmp = i;
do {
count[tmp % 10]++;
tmp /= 10;
} while(tmp);
}
for (i = 0; i < 10; i++) {
std::cout << i << " appears " << count[i] << " times" << std::endl;
}
return 0;
}
My solution is like this:
int main(){
int s,k;
cin >> s >> k;
int numbers[10]={0};
string sum;
for(int i=s;i<=k;i++)
{
sum=to_string(i);
for(int i=0;i<sum.length();i++){
numbers[(int)sum.at(i)-48]++;
}
}
for(int i=0;i<10;i++){
cout<<numbers[i]<<endl;
}
return 0;
}
public static void getDigitsInBook(int n) {
for(int i=0;i<10;i++) {
int x = n,val=0,k=1;
while(x!=0) {
int left = x/10;
int num = x%10;
int right = n%k;
if(i == 0) {
val = val+ (left*k);
}
else if(i<num) {
val = val + ((left+1)*k);
}
else if(i==num) {
val = val + (left*k) + right+1;
}
else {
val = val+ (left*k);
}
k=k*10;
x = n/k;
}
System.out.println(val);
}
}
What you usually do with such tasks is calculating the number between 0 and S and between 0 and K and subtracting those.
How many are between 0 and 767? First count the numbers of the last digit. There are 77 times 0, 1, 2, 3, 4, 5, 6, 7 each and 76 times 8 and 9. More formally, 767/10+1 between 0 and 767%10 and 767/10+1 on the rest. Then calculate the number of occurences of the last digit for 767/10=76, multiply by 10, add 7 times 7 and 6 (for the error on the last one) and do the same for the remaining digits, here 76/10=7. Finally, add the results up.
This solves the problem in O(log_10 K).
try this code:
for(int n=s ; n<=k ; n++)
{
tempN = abs(n);
while(tempN > 0)
{
tempDigit = tempN % 10;
tempN /= 10;
//count tempDigit here
}
}
assuming your variables are ints, "tempN /= 10;" should be no problem.