↜ Back to index Introduction to Numerical Analysis 2
Solutions for Lecture 1
Exercise 3
implicit none
real a, b, c, d, x, y, t
print *, "Enter a, b and c"
read *, a, b, c
! the determinant
= b**2 - 4 * a * c
d
if (d < 0.0) then
print *, "There are no real solutions"
else if (d == 0.0) then
print *, "One solution"
print *, "x1 = ", -b / (2 * a)
else
= (-b - sqrt(d)) / (2 * a)
x = (-b + sqrt(d)) / (2 * a)
y
if (x > y) then
= x
t = y
x = t
y end if
print *, "Two solutions"
print *, "x1 = ", x
print *, "x2 = ", y
end if
end
- In general, tests for equality of
real
numbers should be done more carefully thand == 0.0
.
Exercise 4
implicit none
real a, b, c, t
print *, "Enter a, b and c"
read *, a, b, c
if (a > b) then
! swap a and b
= a
t = b
a = t
b end if
if (b > c) then
! swap b and c
= b
t = c
b = t
c end if
if (a > b) then
! swap a and b
= a
t = b
a = t
b end if
print *, a, b, c
end
Exercise 5
implicit none
integer n, f, i
print *, "Enter n"
read *, n
= 1
f
do i = 1,n
= f * i
f end do
print *, "Factorial of ", n, " = ", f
end
Exercise 6
implicit none
integer a, b, n, t, i
print *, "Enter n"
read *, n
= 0
a = 1
b
if (n == 0) then
= a
b else if (n == 1) then
! do nothing
else
do i = 2,n
= b
t = a + b
b = t
a end do
end if
print *, "Fibonacci ", b
end
Exercise 7
implicit none
integer n, j, m
print *, "Enter n"
read *, n
= 1
m do j = 2, n - 1
if (mod(n, j) == 0) then
= 0
m exit
end if
end do
if (m == 1) then
print *, "yes"
else
print *, "no"
end if
end
implicit none
integer n, i, j, m
print *, "Enter n"
read *, n
do i = 2, n
= 1
m do j = 2, i - 1
if (mod(i, j) == 0) then
= 0
m exit
end if
end do
if (m > 0) then
print *, i
end if
end do
end
implicit none
integer n, k, j, m
print *, "Enter n"
read *, n
= 2
k do while (n > 0)
= 1
m do j = 2, k - 1
if (mod(k, j) == 0) then
= 0
m exit
end if
end do
if (m > 0) then
print *, k
= n - 1
n end if
= k + 1
k end do
end
implicit none
integer, parameter :: n = 1000
integer sieve(2:n)
integer i, k
do i = 2, n
= 1 ! 1 indicates that i is a prime
sieve(i) end do
do i = 2, n
if (sieve(i) == 1) then
print *, i
do k = 2, n / i
* i) = 0 ! multiples of i are not primes
sieve(k end do
end if
end do
end