Help with simple Fortran program

  • Context: Fortran 
  • Thread starter Thread starter eku_girl83
  • Start date Start date
  • Tags Tags
    Fortran Program
Click For Summary
SUMMARY

The forum discussion centers on a Fortran program designed to print the prime factorization of a number using trial division. The initial implementation fails to correctly factor numbers beyond powers of 2 due to the placement of the variable initialization for 'i'. The solution involves moving the initialization of 'i' outside the loop to ensure it increments properly for all factors. This adjustment allows the program to continue trial division beyond the first factor.

PREREQUISITES
  • Fortran programming language fundamentals
  • Understanding of trial division algorithm for prime factorization
  • Basic knowledge of control structures in programming (loops and conditionals)
  • Familiarity with integer data types in Fortran
NEXT STEPS
  • Study Fortran control structures, focusing on loops and conditionals
  • Learn about optimization techniques for prime factorization algorithms
  • Explore advanced number theory concepts related to prime factorization
  • Investigate debugging techniques in Fortran to troubleshoot similar issues
USEFUL FOR

Fortran programmers, computer science students, and anyone interested in algorithms for prime factorization.

eku_girl83
Messages
89
Reaction score
0
I need to write a program that will print the prime factorization of a number.
Here's what I have so far:
integer:: n,i

print *, "enter integer"
read *, n
do while (n>1)
i=2
if (mod(n,i)==0) then
print *, i
n = n/i
else
i = i+1
end if
end do
end program

I'm just using trial division to find the prime factorization. For some reason, the program works for powers of 2 (4,8,16,32,64, etc.) but nothing else. It will factor a number such as 20 into (2,2) but doesn't go any farther. What is wrong with my program? Why does it stop trial division at i=2?
 
Technology news on Phys.org
Change this:

do while (n>1)
i=2

I think that you need write:

i=2
do while (n>1)
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 28 ·
Replies
28
Views
5K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 19 ·
Replies
19
Views
7K
  • · Replies 13 ·
Replies
13
Views
3K