Still have questions? Join our Discord server and get real time help.
Log in to vote

Evaluate if a number is considered a happy number in the least amount of characters? [closed]

Asked by
Fifkee 2017 Administrator Moderation Voter Community Moderator
5 months ago
Edited 4 months ago

For more clarification, a number is happy when the sum of the square of all numbers within a given number is equal to 1. If you enter a loop when calculating the happy number, that means the number is unhappy. :(

Print statements are not part of your character count. Your code should explicitly state if the number is happy or otherwise.

Example: 19 -> (1^2 + 9 ^2) = 82 -> (8^2 + 2^2) = 68 -> (6^2 + 8^2) = 100 ->(1^2 + 0^2 + 0^2) = 1. This means that 19 is a happy number.

Shortest and most valid answer within a week gets the solution. If you've gotten an answer on the Discord, you are not a valid contester. I'll update the question with my implementation within due time.

And, before you prepare your moderation voter hammer, it's in-line with all rules and regulations. I checked thrice.


My answer:

local t,y,b,x={},tonumber,29;function h(n)if(t[n])then;return(false)end;t[n]="";b=0;for _ in(tostring(n):gmatch('%d'))do;b=b+(y(_)or(0))^2;end;if(b<=1)then;return("")end;print(b)return(h(b))end;print(h(b)~=false)

Locked by JesseSong

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

1 answer

Log in to vote
Answered by 5 months ago
Edited by JesseSong 24 days ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your answer.

I did it: here is my solution.

function isHappy(originalNumber)
    local pattern = {};
    function calculate(number)
        local squaredSum = 0;
        for num in tostring(number):gmatch("(%d)") do --parses a number to individual digits
            squaredSum = squaredSum + (tonumber(num) ^ 2) 

        if(not pattern[tostring(squaredSum)]) then
            pattern[tostring(squaredSum)] = 0;
        pattern[tostring(squaredSum)] = pattern[tostring(squaredSum)] + 1;
        if(squaredSum == 1) then
            return true
        elseif(pattern[tostring(squaredSum)] > 1) then
            return false
            return calculate(squaredSum)

    local _isHappy  = calculate(originalNumber)
    if(_isHappy) then
        print(originalNumber, " is happy (:")
        print(originalNumber, " is sad ):")

isHappy(10) --happy
isHappy(12) --sad