1

https://open.kattis.com/problems/pot

Pot

The teacher has sent an e-mail to her students with the following task: “Write a program that will determine and output the value of X if given the statement:

X = number1pow1 + number2pow2 + … + numberNpowN

and it holds that number1, number2 to numberN are integers, and pow1, pow2 to powN are one-digit integers.” Unfortunately, when the teacher downloaded the task to her computer, the text formatting was lost so the task transformed into a sum of N integers:

X = P1 + P2 + … + PN

For example, without text formatting, the original task in the form of X = 212 + 1253 became a task in the form of X = 212 + 1253. Help the teacher by writing a program that will, for given N integers from P1 to PN determine and output the value of X from the original task.

Input:

The first line of input contains the integer N (1 ≤ N ≤ 10), the number of the addends from the task. Each of the following N lines contains the integer Pi (10 ≤ Pi ≤ 9999, i = 1 … N) from the task.

Output:

The first and only line of output must contain the value of X (X ≤ 1000000000) from the original task.


I recently just started coding in C++ and was told Kattis was a good website to start practicing on. I have started to freshen up on the basics for my upcoming CS 2 class in the fall and I am confused why my answer is not getting accepted. Any answers would be greatly appreciated!

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int nums, number, total, temp;
    cin >> nums;

    for (int i = 0; i < nums; i++) {
        cin >> number;
        temp = number % 10;
        number = number / 10;
        total = total + pow(number, temp);
    }

    cout << total;
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
Booboo
  • 21
  • 2
  • 3
    Initialize `total`. – Swordfish Jul 28 '20 at 02:46
  • 4
    Declare variables as close to where they're needed as possible. – Swordfish Jul 28 '20 at 02:47
  • 2
    Use `/=` and `+=` for better readability. – Swordfish Jul 28 '20 at 02:48
  • Thank you! Setting total = 0 gave an accepted answer. – Booboo Jul 28 '20 at 02:51
  • 3
    @Booboo The problem with your solution is that it could lead to [erroneous results if pow() is used](https://stackoverflow.com/questions/25678481/why-does-pown-2-return-24-when-n-5-with-my-compiler-and-os). The bottom line is to not use `pow` to compute powers using integer exponents, unless the final result is too large to be represented as an integer. – PaulMcKenzie Jul 28 '20 at 03:50

0 Answers0