# Day 19: Interfaces

# Day 19: Interfaces

saxtorff + 11 comments No Python?! :-(

ps_nz + 2 comments My thoughts, too. I've done everything so far in Python 3, pity that I either switch to another language or forgo completing this programming problem.

pavanichilakala + 0 comments [deleted]deepeshNair + 0 comments [deleted]

varun_pikachu + 7 comments Python doesn't support interfaces(and doesn't need to). Python has powerful multiple inheritance anyways, so languages like Java which have single inheritance only have to cope by inculcating "implementable" interfaces.

nasimso + 5 comments [deleted]bs118636 + 0 comments What does this have to do with interfaces in OOP?

JKDos + 0 comments You are confusing Interfaces and GUI for the same thing

gustavoferreira + 0 comments LOL........

Interfaces in OO != Interfaces in GUI!!!

tbtitans21 + 1 comment Why does this get deleted? I want to see what was downvoted. Does no one believe in freedom of speech anymore that even when something obviously bad is written and downvoted by many members of the community we can't see what is not generally accepted? I want to see how NOT to think and this doesn't help that I can't see what they said that was downvoted so much.

gustavoferreira + 0 comments I remember this. The guy was talking about GUI interfaces which has nothing to do with interfaces in object oriented programming.

He probably deleted his own comment, don't know.

d_seibert121 + 1 comment They could have used the closest thing to interfaces in Python, i.e. Abstract Base Classes.

Inkling + 0 comments There was already an exercise for that though.

robertwilk + 0 comments "powerful multiple inheritance" which is more often abused than drugs leading to some of the most ridiculously structured and embarasing code. Responsible developers of other languages which support MI (like C++) caution against it's misuse; way too easy to go around shooting yourself in the foot.

lonso + 0 comments I've actually used interfaces with Python. It's just creating a class that only has methods, and make sure not to initialize it, just inherit the methods. They are called mixins no?

budnikav86 + 0 comments Intefaces has totally different purposes than multiple inheritance. It's an important part of big project development. Interfaces similar to abstract classes, but has some difference for specific purposes. Interfaces more flexible than abstract classes, but still preserve implementation of some methods in inhereted class.

jacomatic + 0 comments in python interfaces are supported they are implicit though we could have built something equivelent it just would not be typed as an interface.

ScienceD + 0 comments C++ has powerfull multiple inheritance too, but It don't thow away interfaces!

pavanichilakala + 7 comments what is wrong in my code.Iam not get output public int divisorSum(int n) { int sum =0; int i=0; while( i<=n) { if(n%i==0) sum=sum+i; i++; } return sum; }

SwackOverflow + 0 comments Your counter for the while loop starts at 0. It will compute the remainder modulo 0 in this first case, which does not make any sense.

AryaCAchari + 0 comments change into int i = 1; insted of int i = 0;

sriram301296 + 1 comment Another point to note, is that After n/2, the only factor of n will be n itself. This reduces the running time of the whole algorithm

Abhilash_Medhi + 1 comment sqrt(n) will reduce it more.

just add i and n/i(if a pure int)

hashem_omar_717 + 1 comment how is this correct for a number like 20? 10 is larger than sqrt(20), am confused here

luchillo17 + 2 comments You're right, if we were talking prime numbers,

`sqrt(n)`

would make sense, but not for divisors.**[Edit]:**Let me correct myself, if you add`i`

and`n / i`

at the same step, you're adding the other number that is also a divisor in same step, take for example`8`

, if`i`

is`2`

, you'll end up adding`sum += 2 + 8/2`

which traduces to`sum += 2 + 4`

, both`2`

&`4`

are divisors of`8`

, keep doing that and you'll soon notice that this way the`i`

variable only needs to go up to`sqrt(n)`

.hashem_omar_717 + 0 comments yes i got it thank you very much

safeer_raees + 0 comments If n=1, then this would return 2, no? even though it should return 1.

sumitsrbh + 0 comments Use proper format when u paste code.

arshad701 + 2 comments Here is a tip, a number's divisor will always be 1 and the number itself. So you can initialize the sum as n+1 itself. And the start the loop from i=2 till i<=n/2 because the greatest divisor of the number will not be greater than its half. Hence by this you shorten your for loop. Also place a condition at start for n=1 then just return 1. Otherwise that test case wont be successful

hashem_omar_717 + 1 comment i think this would fail for the case of 1, n+1 will be 2 where the correct answer is just 1

rtrios006 + 0 comments To account for a special case like 1, you one can leverage the ternary operator to assign value to sum like so:

int sum = (n==1) ? 1 : n+1;

This will mitigate logic errors in code later on.

maikee + 0 comments thanks! this worked for me

pawanadubey + 0 comments This one worked for me.. class Calculator implements AdvancedArithmetic{ public int divisorSum(int n){ int sum=n; for(int i=1;i<=n/2;i++){ if(n%i == 0){ sum=sum+i; } } return sum; } }

[deleted] + 0 comments put that i++ outside of if condition.

int sum=0; int i=1; while(i<=n) { if(n%i==0) { sum+=i; } i++; }

Xarmanla + 0 comments Sadly, I, too, had to fall back to annother language. I choose C# and I had to remember the semicolons and variable declaration.

jakehku + 0 comments This is what i found on stackoverflow

Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.

And the difference between abstract and interface is a hairsplitting thing when you have duck typing.

Java uses interfaces because it doesn't have multiple inheritance.

http://stackoverflow.com/questions/372042/difference-between-abstract-class-and-interface-in-python

gourde_david + 0 comments This is lame, they should ask us to answer with an abtract class in Python...

ElizaW + 0 comments crying to see there's no such an option.....won't be able to complete all 30 questions, unless I turn back to learn Java T.T

aliuakbar + 0 comments This would do it in python:

x = int(input("your input"))

sum = 0 for i in range(1, x + 1): if x % i == 0: sum += i else: i += 1 return sum

mikebloom914 + 2 comments PYTHON3 SIMPLE SOLUTION!

x = [] for i in range(1, n+1): if n % i == 0: x.append(i) else: pass return sum(x)

tomazurkiewicz + 1 comment Simple one-liner:

return sum([i for i in range(1,n+1) if(n%i==0)])

firdosh + 0 comments or using an in-built function is_integer()

return sum([ii for ii in range(1, n+1) if (n/ii).is_integer()])

m_den + 1 comment This range doesn't make any sense. After the middle you don't need to check all values. You should have taken the range(1, n//2+1). And the beginning value of summ is n. Because the number can always be divided by itself.

adalseno + 1 comment You are right, then

`return sum([i for i in range(1,n//2+1) if n%i == 0])+n`

;-)

wafello + 0 comments That is still not very good - You should only go to sqrt(n) + 1. It really makes the difference - try running it for some little bigger number like 1 billion or more - it is more than 10000 times slower then it could be for 1 billion for example :) Of course when going only to sqrt(n) + 1, You need to do an extra step, but You will come up with it

thallesurzedo + 0 comments basically u just need to make a fucntion to check if a n is divisible by a number from 1 to 1000 or not, and summ all the numbers that are divisors of n.

`class Calculator(AdvancedArithmetic): def divisorSum(self, n): p=0 e=0 for i in range(1,1001): e=(n%i) if e==0: p+=i return p pass`

kurtispykes + 0 comments class Calculator(AdvancedArithmetic): def divisorSum(self, n): factor_sum = 0 for i in range(1, n+1): if n % i == 0: factor_sum += i return(factor_sum)

Bob_Roebling + 10 comments C# - Just kept it simple, I'm sure the performance geeks are screaming.

public class Calculator : AdvancedArithmetic { public int divisorSum(int n) { int sum = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) sum += i; } return sum; } }

JKDos + 4 comments I like this one, it's clean and easy to follow.

Also, since it's a one liner

`for loop`

, you should be able to getaway with removing the curley braces.for (int i = 1; i <= n; i++) if (n % i == 0) sum += i;

DJPeanutButter + 3 comments I mean, since we're shortening code...

for (int i=1;i<=n;sum+=(n%i++?0:i-1));

nidhimadappa + 1 comment You could, but not considered a good programming practice from the point of view of readability and avoiding strange bugs

ScienceD + 0 comments Using loops without brackets when it using only 1 line is totally readable. If you push too much in one line, its not ok. Guys shoud have used ternary operator for real 1 line here. There is basically 2 lines

for (int i = 1; i <= n; i++) { if (n % i == 0) sum += i; }

This should be like this for 100% readability.

ScienceD + 0 comments Agree, I think its much better readability if we use curly brackets only if a loop or if() statement has more than 2 lines. I hate when people use brakets liket this thou:

for (int i = 1; i <= n; i++) { if (n % i == 0) sum += i; }

Better readable like this:

for (int i = 1; i <= n; i++) { if (n % i == 0) sum += i; }

nisarg_1611 + 0 comments we need to check till halfway only (n/2).

dropyghost + 3 comments at least you could stop checking at

`n/2`

and add`n`

at the endInkling + 3 comments Yeah it's a very easy optimization, here's how mine looked:

class Calculator : AdvancedArithmetic { public int divisorSum(int n) { int sum = n; for (int i = 1, half = n/2; i <= half; i++) { if (n % i == 0) sum += i; } return sum; } }

raviloga316 + 0 comments [deleted]nuhman + 0 comments That's clever

dashingakd + 0 comments u diid't declare half?

wy218032 + 0 comments [deleted]wy218032 + 1 comment //we could stop at sqrt(n) //This is my Java solution. I think this may be better. class Calculator implements AdvancedArithmetic{ public int divisorSum(int n){ int sum = 0; for(int i = 1; i <= (int)Math.sqrt(n); i++) { if(n%i==0){ sum = sum + i + n/i; } } if((int)Math.sqrt(n)*(int)Math.sqrt(n)==n){ sum -= Math.sqrt(n); } return sum; } }

nuhman + 2 comments I din't understand why you are doing the

if((int)Math.sqrt(n)*(int)Math.sqrt(n)==n){ sum -= Math.sqrt(n); }

part. Can you explain?

impex_ua + 0 comments If n is square number, you have to minus sqrt n. Just math.

toraju + 1 comment You can optimize that one step to the following... to avoid correction for doubble addition, when input number is an exact square.

public int divisorSum(int n){ int sum = 0;int i; for( i = 1; i <(int)Math.sqrt(n); i++) { if(n%i==0){ sum = sum + i + n/i; } } if(i*i == n){ sum = sum+i; } return sum; }

Ankurjain04 + 0 comments sum = sum+i; should be sum = sum-i;

[deleted] + 1 comment Simple code is the best :)

janakimarshj + 0 comments ss u r correct @gowthambala1200 know this very well

douglas_bell + 1 comment You missed the bounds checks.

if (n >= 1 || n <= 1000) {...

ju7847 + 0 comments Nobody really checks those...

RodneyShag + 1 comment Performance geek here. Nice job. You might want to try improving the runtime by only iterating up to the square root of n instead of n like this to improve your runtime from O(n) to O(n^(1/2)).

Hope this helps.

jiwan_chung + 1 comment any explainations for iterating up to sqrt(n)? and could you please explain sum += i + n/i; part as well?

Thank you.

RodneyShag + 1 comment Iterating up to sqrt(n) makes our runtime improve from O(n) to O(n^(1/2)). When we are checking a number for divisors, we want to find 2 numbers that multiply into a 3rd number, like this:

a * b = c

In my code, the variables are named differently, so we want

i * n/i = n

Every time we find 1 divisor

**i**, we also add the other divisor**n/i**to our sum. Since we are adding both sets of divisors, we can get all of them iterating just up to the sqrt(n). If we kept iterating, we would get duplicates.As an example, if i = 2, n/i = 5, n = 10, we would get 2 * 5 = 10, so we grab both divisors: 2 and 5. If we kept iterating past the square root, we would eventually reach i = 5, n/i = 2, and n = 10, and we would again grab divisors: 5 and 2. We don't want that, so we stop iterating when we reach the square root.

impex_ua + 1 comment My realization of what you suggested:

public int divisorSum(int n) { if (n == 1) return 1; int sum = 0; for (int div = 1; div*div <= n; div++){ sum += n % div == 0 ? div + n / div : 0; } return Math.sqrt(n) % 1 == 0 ? sum - (int) Math.sqrt(n) : sum; }

RodneyShag + 1 comment Nice. This line looks a little weird to me:

Math.sqrt(n) % 1 == 0

Any integer % 1 is always 0. So it seems that line is just checking if the square root of

**n**is an integer or not.impex_ua + 0 comments yes, that's what I do to avoid checking

sum += n == divisor ? 0 : divisor;

inside the loop.

DavidAnatolieIs1 + 0 comments I am on your side! My code is similar to yours - one for loop, simple and clean.

ScienceD + 1 comment Better use ternary for 1 liner if.

struct Calculator : public AdvancedArithmetic { int divisorSum(int n) { int sum = 0; for(int i = n; i > 0; --i) sum += n%i ? 0 : i; return sum; } };

rizulchauhan5 + 0 comments nice yll its really helped me

salazar3593 + 0 comments [deleted]salazar3593 + 0 comments Did your code compile? Because they told us to not use the public keyword for class definition, only for method definition...because were defining multiple classe in one file.☝

lampuiho + 0 comments At least only do the loop up to sqrt of n lol

RodneyShag + 6 comments ### Efficient O(n^(1/2)) solution

From my HackerRank solutions.

Runtime: O(n^(1/2))

Space Complexity: O(1)public int divisorSum(int n) { int sum = 0; int sqrt = (int) Math.sqrt(n); // Small optimization: if n is odd, we can't have even numbers as divisors int stepSize = (n % 2 == 1) ? 2 : 1; for (int i = 1; i <= sqrt; i += stepSize) { if (n % i == 0) { // if "i" is a divisor sum += i + n/i; // add both divisors } } // If sqrt is a divisor, we should only count it once if (sqrt * sqrt == n) { sum -= sqrt; } return sum; }

shareef_hiasat + 1 comment can you please share us where i can find that n^1/2 is better than n ?

RodneyShag + 0 comments You can graph y = x^(1/2) and also graph y = x on the same graph. See which one increases faster as you go from left to right on the graph. After graphing, does that make any sense? Since y = x increases faster, it means the solution is not very scalable.

joshiii + 1 comment can you please tell me why you negation of the sum.

RodneyShag + 1 comment If sqrt is a divisor, we end up counting it twice. We do

`sum -=sqrt`

to basically remove the double-count we did earlier.M_F_H + 1 comment it would be slightly more efficient, though, to do

`for(... i < sqrt ...)`

and`if (sqrt*sqrt==n) sum += sqrt;`

in the end.m1k2zoo_km + 0 comments Not really. sqrt is obtained by integer casting; what you suggested might end up not accounting for some of the divisors.

Say n = 6. Then sqrt = (int) Math.sqrt(6) = 2 So your loop would run only once with this statement: sum += 1+6

After that, i < sqrt so we exit the loop. Since 2*2 != 6, you don't add 2 to the sum.

So your suggested modification would result in sum = 7 for n = 6, which is the wrong sum.

You have probably caught this but for anyone who have not, always pay close attention to the difference between (< vs <= ) when you do integer casting!

maxvetrov555 + 0 comments [deleted]maxvetrov555 + 0 comments [deleted]maxvetrov555 + 1 comment I added some optimisations(there is the half of operations if the number n is odd).

What do you think about it?

class Calculator : public AdvancedArithmetic { public: int divisorSum(int n) { int sum = n + 1; const int s = sqrt(n); const int di = 1 + (n & 1); for(int i = di + 1; i <= s; i += di) { if (n % i == 0) { sum += i + n / i; } } if (s * s == n) sum -= s; return sum; } };

RodneyShag + 1 comment Nice optimization. I've updated my solution using your suggestion.

maxvetrov555 + 1 comment Thanks. I starred your project.

Also I think "n & 1" is faster than "n % 2".

(Of course, if a compiler doesn't do the optimisation).

PS. Fix the link. It's broken.

RodneyShag + 0 comments Thanks for star. Fixed the link. You're right, n & 1 is probably faster.

kushguptacse + 0 comments little optimezd solution -

https://www.hackerrank.com/challenges/30-interfaces/forum/comments/574259

krylovsentry + 2 comments With test case #6 something wrong. Excpected output just a number, without any sentences about implementation.

SudicodeDotCom + 2 comments I found a more efficient implementation here for those performance geeks. (Prime factorization is even better, but probably overkill.)

**Note:**Linked answer is slightly wrong, looks like they forgot to add the number itself to the sum. But you get the idea.robertotomas_c + 2 comments I actually did that overkill (even though we are limited to ints instead of even longs).

`public int divisorSum (int N){ HashMap<Integer,Integer> primeFactorization = factor(N); int total = 1; for (int p:primeFactorization.keySet()) { System.err.println("considering prime: " +p + " with mult: "+ primeFactorization.get(p)); int factor = 1; for (int i=0;i<primeFactorization.get(p);i++) { factor*=p; factor+=1; } total*=factor; } return total; } private HashMap<Integer,Integer> factor(int n){ HashMap<Integer,Integer> mii = new HashMap<>(); if(isPrime(n)){ mii.put(n,1); return mii; } if (n%2==0){ int m = n; int cnt=0; do{ m/=2; cnt++; }while(m%2==0); mii.put(2,cnt); } double ceil = n/2.0; for (int i = 3; i <= ceil; i += 2) { if ((isPrime(i)) && (n%i == 0)) { int m = n; int cnt=0; do{ m/=i; cnt++; }while(m%i==0); mii.put(i,cnt); } } return mii; } private static boolean isPrime(int num) { if (num < 2) return false; if (num == 2) return true; if (num % 2 == 0) return false; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true; }`

AdHominem + 2 comments What the heck? :D See my solution, this is a one liner even in Java.

robertotomas_c + 0 comments I invite you to read what I responded to because it wasn't just any simple attempt to solve the problem

SudicodeDotCom + 1 comment It's a one liner if you're willing to do a brute force solution. Efficient solutions tend to be more sophisticated.

AdHominem + 2 comments No. Not understanding basic software engineering principles has nothing to do with sophistication. Premature optimization is the root of all evil. In the absence of measured performance issues, any optimization is a HUGE waste of time and a potential bug source. How long did it take you to write your solution? Mine was done in less than a minute. Welcome to real life programming. ;^)

robertotomas_c + 1 comment I've been a programmer in real life for the past couple if decades., so I don't feel unqualified to respond to you here. Congratulations on your answer. However, dense one liners have a faTal flaw in the real world, they are not maintainable. Someone else, or even just you, has to come back and be able to Understand it, and to change Whatever the parts that go into it. For much the same reasons that premature optimization is the root of all evil, subpar clarity is too. It's better to waste white space than to over optimize or Over-stream.

You can't control the time budget that some future programmer is going to have when they come back to your code, and while streamed solutions are notoriously legible, they are very often equally immutable.

mayer_benoit + 0 comments I have no real life programming experience, so thank you for your debate, it was at least interesting for me.

arnold2 + 0 comments It's true, some people spend too much time overoptimizing something that doesn't matter in a particular application. In this case, with the constraint 1<=n<=1000, a simple brute force, especially when you stop at n/2, works very well.

However, if I'm programming something that I know is to be used in a more general fashion, the performance implications here are huge. The code above dramatically reduces the time needed, as the brute force method is very inefficient (particularly for a large n).

maximshen + 0 comments sieve of eratosthenes !

jabberwock + 0 comments You may use wheel factorization and the divisor function. It is a bit tricky, but the resulting code is not too much complicated (just two cycles). Implementing the sieve, you have not to test if the divisor is actually prime.

dillingerjames + 2 comments Here is a simple solution written in Python 3. Surprisingly, many other solutions I see don't realize you don't need to iterate though each number - only the first half.

`def divisorSum(self, n): if n == 1: return 1 else: factor_sum = 1 + n for i in range(2, n//2 + 1): if n % i == 0: factor_sum += i return factor_sum`

kcostya + 0 comments An elegant solution indeed. Thank you for sharing.

vbondarenko1 + 0 comments [deleted]

davecg + 2 comments Why is there no Python option?

This seems like it would be a straightforward example of class inheritance.

aaronbannin + 0 comments [deleted]fcapizzi + 0 comments I think it's because you can use Abstract Base Classes to accomplish that, so they didn't want to have a 'duplicate' lesson.

Sonu_MIshra + 1 comment My Java Code:

class Calculator implements AdvancedArithmetic{

public int divisorSum(int n){

`int c=0; for(int i=1;i<=n;i++){ if(n%i==0){ c+=i; } } return c;`

} }

RodneyShag + 0 comments Nice job. You might want to try improving the runtime by only iterating up to the square root of n instead of n like this to improve your runtime from O(n) to O(n^(1/2)).

Hope this helps.

andrew104 + 0 comments I did everything in JavaScript thus far (except one problem that surprisingly didn't have it) and now this one doesn't have it. I wish I knew at the beginning of this project that I'd have to be using multiple languages.

renjithsraj + 0 comments Language python is not there ?

Sort 338 Discussions, By:

Please Login in order to post a comment