Compiling c code in VsCode doesn't give an accurate result. It should return 4824, but does -1 instead

Viewed 49
#include <math.h>


long long findNb(long long m)
{

    long long count = 0;
    long long volume = 0;
    
    while (volume < m)
    {   
        count++;
        volume += pow(count, 3);
    }
    
    if (volume == m)
    {
        return count;
    }
    else
    {
        return -1;
    }
    

}


int main(void){
int x = findNb(135440716410000);

printf("%ld", x);


}
1 Answers

Weak pow()

A weak pow() might not provide the best integer answer but a value just a tad less than expected. This difference forms an off-by-one due to integer truncation with conversion of pow() result to long long. For integer problems, best to use integer code, not floating point.

// volume += pow(count, 3);
volume += count * count * count;

Potential lack of precision

pow(count, 3); performs a double calculation with typically 53 bits of precision, yet OP's code better with 64-bit integer math. @Eugene Sh. .

Use consistent types and specifier

long long x = findNb(135440716410000);
printf("%lld\n", x);

Save time, enable all compiler warnings

volume += pow(count, 3);
// warning: conversion from 'double' to 'long long int' may change value [-Wfloat-conversion]
Related