Coding Exercise – LUA Programming – SPOJ Online Judge – 15708. Divisibility


The problem is from SPOJ Online Judge [problem description here]

smpdiv Coding Exercise - LUA Programming - SPOJ Online Judge - 15708. Divisibility beginner brute force code implementation LUA programming language SPOJ online judge

Bruteforce each number from x to n is easy to implement. The 1 second limit is enough for any inputs smaller than 100,000.

The following LUA program solves the puzzle.

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
function split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end
 
function work(s)
    n = s[1] --used as numbers
    x = s[2]
    y = s[3]
    for i = x, n do
        if ((i % x) == 0) and ((i % y) ~= 0) then
            io.write(i..' ') -- used as string
        end
    end
    io.write(string.char(13))
end
 
n = tonumber(io.read())
for i = 1, n do
    s = split(io.read(), [[ ]])
    work(s)
end
function split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

function work(s)
	n = s[1] --used as numbers
	x = s[2]
	y = s[3]
	for i = x, n do
		if ((i % x) == 0) and ((i % y) ~= 0) then
			io.write(i..' ') -- used as string
		end
	end
	io.write(string.char(13))
end

n = tonumber(io.read())
for i = 1, n do
	s = split(io.read(), [[ ]])
	work(s)
end

We use % (same as most C-like languages) to do the modulo on integers. The string and numbers can be converted automatically depending on the context (implicitly).

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
249 words
Last Post: The Two Sum Algorithm using HashMap in C++/Java
Next Post: Coding Exercise - LUA Programming - SPOJ Online Judge - 17481. Fun with Sequences (Act 5)

The Permanent URL is: Coding Exercise – LUA Programming – SPOJ Online Judge – 15708. Divisibility

Leave a Reply