Fortran Help with simple Fortran program

  • Thread starter Thread starter eku_girl83
  • Start date Start date
  • Tags Tags
    Fortran Program
Click For Summary
The discussion centers on a program designed to print the prime factorization of a number using trial division. The current implementation successfully factors powers of 2 but fails for other numbers, only providing partial results. The issue arises because the variable 'i' is reset to 2 within the loop, preventing it from incrementing beyond 2 during subsequent iterations. To resolve this, the suggestion is to move the initialization of 'i' outside the loop, allowing it to increase properly and continue the trial division process for all potential factors. This adjustment is crucial for the program to function correctly for a wider range of integers.
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)
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

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