Vercas
Vercas

Reputation: 9141

Printing a value makes the program work?

#include <iostream>
#include <cstdio>

using namespace std;

bool numar(unsigned long long n)
{
    return (n > 99) && ((n % 100) == 25);
}

int main()
{
    freopen("numere.in", "r", stdin);
    freopen("numere.out", "w", stdout);

    int cnt = 0;

    unsigned long long n, a, Nblabla, N;

    while (scanf("%d", &n) == 1)
    {
        if (numar(n))
        {
            a = (n - 25) / 100;

            cout << a; // This son of a *****.

            for (N = 1; true; N++)
            {
                Nblabla = N * (N + 1);

                if (Nblabla > a)
                    break;
                else if (Nblabla == a)
                {
                    cnt++;
                }
            }
        }
    }

    printf("%d", cnt);

    return 0;
}

Simply, if I comment that line (cout << a;), the program stops working. If I leave it there, it works.
I'm using Code::Blocks, GNU GCC.

This just checks if a number is the square of a number that ends with the digit 5. (Base 10) (I am not allowed to use square roots)

Before asking, no, this isn't homework. This is my submission to a subject of an online contest.

Can anyone tell me why is this happening?

Upvotes: 2

Views: 72

Answers (1)

md5
md5

Reputation: 23699

With %d format, scanf will try to read a pointer to int. But &n is a pointer to unsigned long long. This leads to an undefined behavior, which could be the reason of your strange result.

The right format is %llu.

Upvotes: 1

Related Questions