﻿Coding to solve Math problems 编程解数学题 | 悉尼数学补习,家教,辅导,补课 Sydney Mathematics Coaching,Math Tutor

## Coding to solve Math problems 编程解数学题

Here we use Lua programs to solve Math problems.

1. Convert fraction to decimal. 将分数转换为小数
print(‘ENTER NUMBER’)
for i=1,n,1 do
print(‘1/’,1+i,’=’,1/(1+i))
end

2. Series 数列 2,3,5,8,12,17,……
print(‘enter number’)
print (‘2′)
m=2
j=1
for i=1,n do
m=m+j
print(m)
j=j+1
end

3. Times 9 Multiplication Table 乘9的乘法表
a=1
b=9
for i=1,9 do
print(a,’*’,b,’=’,a*b)
a=a+1
end
–IT WORKS OK

4. Fibonacci Series 斐波那契数列 1,1,2,3,5,8,13,21,……
print (‘ENTER NUMBER’)
a=1
b=1
print(a,b)
i=2
while i《 n do
i=i+1
c=a+b
print(c)
a=b
b=c
end

5. Sum of First N natural numbers 求前n个自然数之和
print(“Sum of First N natural numbers”)
— loop method
function nsum1(n)
local sum = 0
for i = 0, n do
sum = sum + i
end
return sum
end
— recursive method
function nsum2(n)
if n == 0 then
return 0
else
return n + nsum2(n-1)
end
end
— formula method
function nsum3(n)
return n * (n + 1) /2
end
— get N
print(“enter value of N ?”)
— calc sum
print( “Loop Sum1 = “..nsum1(n) )
print( “Recursive Sum2 = “..nsum2(n) )
print( “Formula Sum3 = “..nsum3(n) )

6. Sum of some positive and negative squares 正负平方数求和 1^2-2^2+3^2-4^2+……
print (‘ENTER NUMBER’)
sum=0
for i=1,n do
if math.fmod(i,2)==0
then sum=sum-i*i
else sum=sum+i*i
end
end
print (‘sum=’,sum)

7. Sum of square of First N natural numbers 前n个自然数平方和
print(‘below ENTER NUMBER’)
sum=0
for i=1,n do
sum=sum+i*i
end
print (‘sum=’,sum)

8. Sum of series 数列求和 1*2+2*3+3*4+4*5+……
print (‘ENTER NUMBER’)
sum=0
for i=1,n do
sum=sum+i*(i+1)
end
print (sum)

9. Print stars 打印星号
print(‘Hello ‘ .. name)
repeat
print(‘How many Stars do you want?’)
s = ”
for i = 1, n do
s = s .. ‘*’
end
print(s)
print(‘Do you want more Stars (y/n)?’)
until m ~= ‘y’
print(‘Goodbye ‘ .. name)

print(“a x^2 + b x + c = 0”)
print(“Enter Value of a ?”)
print(“Enter Value of b ?”)
print(“Enter Value of c ?”)
d = b^2 – 4 * a * c
print(“Discriminant = “..d)
if d > 0 then
print(“Positive Discriminant, two solotions:”)
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b – math.sqrt(d)) / (2 * a)
print(“x = “..x1)
print(“x = “..x2)
elseif d 《 0 then
print(“Negative Discriminant, two imaginary solutions:”)
r = -b / ( 2 * a)
i = math.sqrt(-d) / (2 * a)
print(“x = “..r..” + “..i..” i”)
print(“x = “..r..” – “..i..” i”)
else
print(“Zero Discriminant, one solution:”)
x = -b / (2 * a)
print(“x = “..x)
end

11. Circle & Sphere Formulas 利用圆和球的公式求解
print(“Circle & Sphere Formulas”)

c = 2 * math.pi * r
print(“Circle Circumference = “..c)

a = math.pi * r^2
print(“Circle Area = “..a)

s = 4 * math.pi * r^2
print(“Sphere Surface Area = “..s)

v = 4 / 3 * math.pi * r^3
print(“Sphere Volume = “..v)