Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

find largest prime factor (problem #3) #2

Open
wants to merge 3 commits into from

1 participant

Commits on May 9, 2012
  1. @nuex
Commits on May 29, 2012
  1. @nuex

    use an accumulator

    nuex authored
  2. @nuex
This page is out of date. Refresh to see the latest.
Showing with 28 additions and 0 deletions.
  1. +28 −0 largest_prime_factor.escript
View
28 largest_prime_factor.escript
@@ -0,0 +1,28 @@
+#!/usr/bin/env escript
+%%! -smp enable -sname largest_prime_factor
+
+%%%
+%%% The prime factors of 13195 are 5, 7, 13 and 29.
+%%% What is the largest prime factor of the number 600851475143 ?
+%%%
+
+main([String]) ->
+ N = list_to_integer(String),
+ PrimeFactors = pfac(N),
+ Max = lists:max(PrimeFactors),
+ io:format("largest prime factor: ~w = ~w\n", [N, Max]);
+main(_) ->
+ usage().
+
+usage() ->
+ io:format("usage: number\n"),
+ halt(1).
+
+pfac(N) ->
+ pfac(N, 2, []).
+pfac(N, D, Factors) when N rem D == 0, N > 1 ->
+ pfac(round(N / D), D + 1, [D|Factors]);
+pfac(N, D, Factors) when N > 1 ->
+ pfac(N, D + 1, Factors);
+pfac(_N, _D, Factors) ->
+ Factors.
Something went wrong with that request. Please try again.