def gcd(m, n)
	if m < n 
		gcd(n, m)
	elsif n == 0
		m
	else
		gcd(n, m % n)
	end 
end

def compute_lcm(m, n)
	m * n / gcd(m, n)
end

class Array
	def accum
		ac = Array.new(size + 1)
		ac[0] = 0
		(1..size).each do |i|
			ac[i] = ac[i-1] + self[i-1]
		end
		ac
	end
end

class LCMTree
	def initialize(a, l, r)
		@l, @r = l, r
		if l == r
			@lcm = a[l]
			@left = @right= nil
		else
			@left= LCMTree.new(a, l, (l+r)/2)
			@right= LCMTree.new(a, (l+r)/2+1, r)
			@lcm = compute_lcm(@left.lcm, @right.lcm)
		end
	end

	def lcm(l = @l, r = @r)
		if l == @l && r == @r
			@lcm
		elsif r <= @left.r
			@left.lcm(l, r)
		elsif @right.l <= l
			@right.lcm(l, r)
		else
			compute_lcm(@left.lcm(l, @left.r), @right.lcm(@right.l, r))
		end
	end

	attr_reader :l, :r
end

n, q = gets.split.map(&:to_i)
perm = [nil] + gets.split.map(&:to_i)

cycle = Array.new(n+1)
add_per_perm = Array.new(n+1)
(1..n).each do |x0|
	k = 1
	x = perm[x0]
	add_per_perm[x0] = x
	until x == x0
		k += 1
		x = perm[x]
		add_per_perm[x0] += x
	end
	cycle[x0] = k
	add_per_perm[x0] /= k.to_f
end
add_per_perm.shift
accum = add_per_perm.accum

t = LCMTree.new(cycle, 1, n)

q.times do
	l, r = gets.split.map(&:to_i)
	k = t.lcm(l, r)
	add = accum[r] - accum[l-1]
	p (add * k).to_i % 1000000007
end