Coding to solve Math problems 编程解数学题

Here we use Lua programs to solve Math problems.
这里我们使用Lua程序来解数学题(其它程序语言也可以)

1. Convert fraction to decimal. 将分数转换为小数
print(‘ENTER NUMBER’)
n=io.read(“*n”)
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’)
n=io.read(“*n”)
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’)
n=io.read(“*n”)
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 ?”)
n = io.read(“*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’)
n=io.read(“*n”)
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’)
n=io.read(“*n”)
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’)
n=io.read(“*n”)
sum=0
for i=1,n do
sum=sum+i*(i+1)
end
print (sum)

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

10. Quadratic Equation Solver 求解一元二次方程
print(“Quadratic Equation Solver”)
print(“a x^2 + b x + c = 0”)
print(“Enter Value of a ?”)
a = io.read(“*n”)
print(“Enter Value of b ?”)
b = io.read(“*n”)
print(“Enter Value of c ?”)
c = io.read(“*n”)
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”)

print(“Radius ?”)
r = io.read(“*n”)

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)