1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>


long long str2longlong(const char *str);
long square_sum(long long num);
long pow_long(long x, long y);


int main(int argc, char const *argv[])
{
	if (argc != 4){
		fprintf(stderr, "Wrong number of arguments. Usage: %s k a b\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	long long a, b, k;
	int counter = 0;

	k = str2longlong(argv[1]);
	a = str2longlong(argv[2]);
	b = str2longlong(argv[3]);

	long long multiplier = (a % k) ? a / k + 1 : a / k;
	long long candidate = k * multiplier;

	// printf("%lld\n", multiplier);
	//printf("%ld\n", square_sum((long)a));

	while (candidate < b){
		if (k * square_sum(candidate) == candidate) {
			//printf("%lld\n", candidate);
			++counter;
		}
		candidate += k;
	}

	printf("%d\n", counter);

	return 0;
}


long square_sum(long long num){
	long res = 0;

	while (num != 0) {
		res += pow_long((num % 10), 2); 
		num /= 10;
	}
	return res;
}


long pow_long(long x, long y){
	int i;
	long res = 1;
	for (i = 0; i < y; ++i)
		res *= x;
	return res;
}


long long str2longlong(const char *str){
	int base = 10;
	char *endptr;
	errno = 0;

	long long res = strtoll(str, &endptr, base);

	if (errno == ERANGE) {
		fprintf(stderr, "Overflow or underflow\n");
		exit(EXIT_FAILURE);
	}

	if (endptr == str) {
        fprintf(stderr, "No digits were found\n");
        exit(EXIT_FAILURE);
    }
    return res;
}