Domanda

I wrote a simple FORTRAN code in order to do the following: assume we have to integer numbers n1 and n2 which have common divisors. For example 3 and 6 both are divided by 3. Here is the code

PROGRAM test

INTEGER i,n1,n2

WRITE(*,*)' Please enter two numbers: '
READ(*,*)n1,n2

DO i=2,10,1
  IF(MOD(n1,i).EQ.0.AND.MOD(n2,i).EQ.0)THEN
     n1=n1/i
     n2=n2/i
  ENDIF
    n1=n1
    n2=n2
ENDDO

WRITE(*,*)n1,n2

PAUSE

END      

This works fine for the example (3,6). However, there are cases like (4,8) in which the numbers have more than one common divisor, in this case 2 and 4. Another example (16,24). I want to compute the maximum common divisor of the two numbers and then reduce them (i.e. 3,6 to 1 and 2), but the code returns the first one (4,8 returns to 2, 4 instead of 1,2). How should it be modified in order to calculate the maximum divisor?

Many thanks in advance!

È stato utile?

Soluzione

You could stay with an i, till your if-statement is false.


In other words:

If a number can be divided by i, then don't immediately go to i+1, but try to divide by i again.


EDIT: I think the easiest way is to use a DO WHILE-loop. To calculate the divisor, you have to multiply all your i.

gcd = 1
DO i=2,10,1
  DO WHILE (MOD(n1,i).EQ.0.AND.MOD(n2,i).EQ.0)
     n1=n1/i
     n2=n2/i
     gcd = gcd * i
  ENDDO
ENDDO
WRITE(*,*) gcd

Altri suggerimenti

What you are looking for is the greatest common divisor. You may do this:

function gcd(a, b)
   implicit none
   integer a, b, aa, bb, cc, gcd

   aa = abs(a)
   bb = abs(b)
   do while (bb .ne. 0)
      cc = mod(aa, bb)
      aa = bb
      bb = cc
   end do
   gcd = aa
end

Note: it is written in Fortran 77 + MIL-STD-1753 (for the DO WHILE construct and IMPLICIT NONE).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top