[gcalctool/vala] Test factorize
- From: Robert Ancell <rancell src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [gcalctool/vala] Test factorize
- Date: Fri, 12 Oct 2012 21:08:20 +0000 (UTC)
commit d3f871dcb49e190a49a60ab1a7acea6aa225f63e
Author: Robert Ancell <robert ancell canonical com>
Date: Sat Oct 13 10:07:00 2012 +1300
Test factorize
src/test-number.vala | 70 +++++++++++++++++++++++++++++++++++++++++++++++++-
1 files changed, 69 insertions(+), 1 deletions(-)
---
diff --git a/src/test-number.vala b/src/test-number.vala
index 01e4ab9..f4d1a9c 100644
--- a/src/test-number.vala
+++ b/src/test-number.vala
@@ -1016,6 +1016,74 @@ private void test_shift ()
pass ();
}
+private void test_factorize ()
+{
+ for (var a = 0; a < 100; a++)
+ {
+ var factors = (new Number.integer (a)).factorize ();
+ var expected = factorize (a);
+
+ var matches = false;
+ if (factors.length () == expected.length ())
+ {
+ matches = true;
+ for (var i = 0 ; i < factors.length (); i++)
+ if (factors.nth_data (i).to_integer () != expected.nth_data (i))
+ matches = false;
+ }
+
+ if (!matches)
+ {
+ var factors_string = "";
+ foreach (var f in factors)
+ {
+ if (factors_string != "")
+ factors_string += ", ";
+ factors_string += "%d".printf ((int) f.to_integer ());
+ }
+ var expected_string = "";
+ foreach (var f in expected)
+ {
+ if (expected_string != "")
+ expected_string += ", ";
+ expected_string += "%d".printf (f);
+ }
+ fail ("(%d).factorize () -> (%s), expected (%s)".printf (a, factors_string, expected_string));
+ return;
+ }
+ }
+
+ pass ();
+}
+
+private List<int> factorize (int number)
+{
+ var factors = new List<int> ();
+ if (number < 2)
+ {
+ factors.append (number);
+ return factors;
+ }
+
+ var n = number;
+ while (true)
+ {
+ for (var factor = 2; factor <= n; factor++)
+ {
+ if (n % factor == 0)
+ {
+ factors.append (factor);
+ n /= factor;
+ if (n == 1)
+ return factors;
+ break;
+ }
+ }
+ }
+
+ return factors;
+}
+
static int main (string[] args)
{
Intl.setlocale (LocaleCategory.ALL, "C");
@@ -1088,7 +1156,7 @@ static int main (string[] args)
test_shift ();
//test_ones_complement ();
//test_twos_complement ();
- //test_factorize ();
+ test_factorize ();
if (fail_count == 0)
stdout.printf ("Passed all %i tests\n", pass_count);
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]