r/dailyprogrammer • u/rya11111 3 1 • Jun 04 '12
[6/4/2012] Challenge #60 [easy]
A polite number n is an integer that is the sum of two or more consecutive nonnegative integers in at least one way.
Here is an article helping in understanding Polite numbers
Your challenge is to write a function to determine the ways if a number is polite or not.
13
Upvotes
4
u/ashashwat Jun 04 '12 edited Jun 05 '12
For every number N, we can write:
(1 + 2 + 3 + ... + n) - (1 + 2 + 3 + .. + k) = N
n(n + 1)/2 - k(k + 1)/2 = N
n <- [1, N] and k <- [1, n]
Therefore running two loops solves this problem in O(N2).
Edit: As Ttl suggested we don't need to run two loops.
However,
From wiki: For every x, the politeness of x equals the number of odd divisors of x that are greater than one. It solves the problem in O(N) with a single sweep.
In Haskell:
Edit: Turns out we can compute odd divisors, greater than 1 in O(sqrt N).
In Haskell:
2
u/emcoffey3 0 0 Jun 04 '12
C#
2
u/BallForce1 Jun 04 '12
C++
1
u/prophile Jun 04 '12
In Python:
1
u/SwimmingPastaDevil 0 0 Jun 04 '12 edited Jun 04 '12
Python:
Edit: Added few lines to print the
politeness1
u/Arthree Jun 04 '12
Autohotkey_L:
1
u/xjtian Jun 04 '12
The politeness lists can include negative integers as well.
Python:
1
u/Cosmologicon 2 3 Jun 04 '12
Cheat method, since it doesn't look like it's been done yet (python):
1
u/cdelahousse Jun 05 '12
Javascript:
1
u/huck_cussler 0 0 Jun 05 '12
1
u/school_throwaway Jun 05 '12
Python
1
u/juror-number-8 Jul 05 '12
Ruby: