C
C
chipoku2020-06-17 06:20:44
C++ / C#
chipoku, 2020-06-17 06:20:44

Why does the program return a negative number when raising the number 17 to the power of 5?

Perhaps someone will find the question ridiculous, but when raising the number 17 to the power of 5, the program returns a negative number. It seems to me that the problem is in memory, but no matter how much free space I allocated, nothing changed. Raised with pow from cmath.

PS I apologize in advance, but I started to learn C++ not long ago.
When you enter the number 17 in "inNums", the output is -2147483648.

#include <iostream>
#include <cmath>

bool testNums(int num) {
  bool test;
  int FLT = pow(5, num) - 5;

  if (FLT % num == 0) {
    test = true;
  }
  else{
    std::cout << false << std::endl;
    return false;	
  }

  if (test == true) {
    std::cout << true << std::endl;
    return true;
  }

}

int main() {
  int inNums;

  while (true) {
    std::cin >> inNums;
    testNums(inNums);
  }

  return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2020-06-17
@chipoku

Integer overflow. Your int is 32 bits, and 5 17 = 762939453125 > 2 39 . Use a 64-bit data type, then you can count up to 5 27 .

V
VitiaKotik, 2020-06-17
@VitiaKotik

The number -2147483648 looks like an overflow.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question