0

I have t test cases. Given two numbers x and n, find number of ways x can be expressed as sum of n-th power of unique natural numbers.

The approach is to either select a number or move to the next one.The ans returned is stored in an array since I am using the dp approach.

This is my code

#include<bits/stdc++.h>
using namespace std;

int arr[101];

int func(int x,int n,int ind)
{
    if(arr[x]!=-1)
    {
        return arr[x];
    }
    if(x==0)
    {
        return 1;
    }
    if(ind>=(sqrt(x)+1))
    {
        return 0;
    }
    if(x<0)
    {
        return 0;
    }

    //you can either take ind or just move to the next one

    arr[x]=func(x-pow(ind,n),n,ind+1)+func(x,n,ind+1);
    return arr[x];
}

int main()
{

    int t;
    cin>>t;
    while(t)
    {

        int ans=0;
        memset(arr,-1,sizeof(arr));

        int x,n;
        cin>>x>>n;

        int ind=1;
        ans=func(x,n,ind);

        cout<<"printing the ans\n"<<ans;
        t--;
    }

    return 0;
}

for input 1 10 2
I am getting printing the ans -297160607 though the ans is 1

Aastha
  • 41
  • 8
  • Not noticing any questions in this. – Ayjay Oct 31 '19 at 09:52
  • 5
    First of all please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Some programmer dude Oct 31 '19 at 09:53
  • 1
    Why not step through your code for this example and check the state as you go, so you can see where it's going wrong? – Rup Oct 31 '19 at 10:04
  • 1
    _"though the ans is 1"_ How do you know? – Lukas-T Oct 31 '19 at 10:08
  • 2
    Think about the order of your conditionals for a few minutes. ([Trace-printing](http://coliru.stacked-crooked.com/a/01733eea6abcb863) the values provides very clear clues.) – molbdnilo Oct 31 '19 at 10:17

1 Answers1

2

I inserted a simple debug output in func. For the given input "1 10 2" x sometimes gets negative. This causes UB when accessing the array, but does not necessarily crash.

You already check if x is less than 0, but after using x. Move the if(x < 0) up and you are done.

In general to avoid such mistakes you should use stl containers like std::array or std::vector. Though it is not garantued by the c++ standard, many implementations will performe bounds checking on operator[] when compiled in debug mode. Or you can use at() where the standard garantuess bounds checking.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30