Index: base/cpp101/factor.cc |
diff --git a/base/cpp101/factor.cc b/base/cpp101/factor.cc |
new file mode 100644 |
index 0000000000000000000000000000000000000000..18fa229c69220ea04d4886a6c2ac1311c7396f64 |
--- /dev/null |
+++ b/base/cpp101/factor.cc |
@@ -0,0 +1,100 @@ |
+// Copyright 2013 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#include <stdio.h> |
+ |
+#include "base/at_exit.h" |
+#include "base/bind.h" |
+#include "base/bind_helpers.h" |
+#include "base/callback.h" |
+#include "base/location.h" |
+#include "base/message_loop/message_loop.h" |
+#include "base/run_loop.h" |
+#include "base/strings/string_number_conversions.h" |
+#include "base/task_runner.h" |
+#include "base/threading/thread.h" |
+#include "base/time/time.h" |
+ |
+namespace { |
+ |
+bool FindNonTrivialFactor(int n, int* factor) { |
+ // Really naive algorithm. |
+ for (int i = 2; i < n; ++i) { |
+ if (n % i == 0) { |
+ *factor = i; |
+ return true; |
+ } |
+ } |
+ return false; |
+} |
+ |
+void FindNonTrivialFactorHelper(int n, int* factor, bool* found) { |
+ *found = FindNonTrivialFactor(n, factor); |
+} |
+ |
+void PrintStatusUpdate(base::Time start_time) { |
+ double num_seconds = (base::Time::Now() - start_time).InSecondsF(); |
+ printf("Waited for %f seconds...\n", num_seconds); |
+} |
+ |
+void PrintStatusUpdateRepeatedly( |
+ const scoped_refptr<base::TaskRunner>& task_runner, |
+ base::Time start_time, |
+ base::TimeDelta print_interval) { |
+ PrintStatusUpdate(start_time); |
+ task_runner->PostDelayedTask(FROM_HERE, |
+ base::Bind(PrintStatusUpdateRepeatedly, |
+ task_runner, |
+ start_time, |
+ print_interval), |
+ print_interval); |
+} |
+ |
+} // namespace |
+ |
+int main(int argc, char* argv[]) { |
+ base::AtExitManager exit_manager; |
+ |
+ if (argc <= 1) { |
+ printf("%s: missing operand\n", argv[0]); |
+ return -1; |
+ } |
+ |
+ int n = 0; |
+ if (!base::StringToInt(argv[1], &n) || n < 2) { |
+ printf("%s: invalid n `%s'\n", argv[0], argv[1]); |
+ return -1; |
+ } |
+ |
+ base::Thread worker_thread("Worker thread"); |
+ CHECK(worker_thread.Start()); |
+ |
+ base::MessageLoop main_loop; |
+ |
+ base::RunLoop run_loop; |
+ |
+ int factor = 0; |
+ bool found = false; |
+ worker_thread.message_loop_proxy()->PostTaskAndReply( |
+ FROM_HERE, |
+ base::Bind(&FindNonTrivialFactorHelper, n, &factor, &found), |
+ run_loop.QuitClosure()); |
+ |
+ PrintStatusUpdateRepeatedly(main_loop.message_loop_proxy(), |
+ base::Time::Now(), |
+ base::TimeDelta::FromSeconds(1)); |
+ |
+ run_loop.Run(); |
+ |
+ worker_thread.Stop(); |
+ |
+ if (found) { |
+ printf("found non-trivial factor %d for %d\n", factor, n); |
+ DCHECK_EQ(n % factor, 0); |
+ } else { |
+ printf("%d is prime\n", n); |
+ } |
+ |
+ return 0; |
+} |