Home > Mobile >  How to check if a number's integers cubed with equal the number
How to check if a number's integers cubed with equal the number

Time:12-15

I recognize this problem is very broad but I'm in need of guidance. I'm a beginner and I have instructions to:

Write a function that takes as an argument, an integer number with a maximum of 8 digits, and returns the sum of the cubes of the digits in the number

For Example:

215 would return 2 * 2 * 2 1 * 1 * 1 5 * 5 * 5 = 134 Write a program that accepts an integer number from the keyboard and then uses the function above to test if the inputted number has the property that the sum of its cubed digits equals the number itself.

For Example:

If the user input was 371 then that input would satisfy this property since 3 * 3* 3 7 * 7* 7 1 *1 * 1 = 371 Allow you program to continue forever until an input of 0 is made. A simple “Yes” or “No” is sufficient as output in this program

The code I wrote is broken, and I'm aware it's very incomplete but I just don't know what to do. How am I supposed to check each digit in the number and cube it to see if this will be true?? Some simple code help would be great.

def cube(num1*num1*num1  num2*num2*num2   num3*num3*num3):
    first= num1*num1*num1
    second= num2*num2*num2
    third= num3*num3*num3

    return cube

def main():
    while True:
        num= input("Enter a number (max 8 digits): ")
        c= num.split()

        choice = input("Stop? Enter YES, otherwise hit enter to continue: ")
        if choice.upper() == "YES":
            break

main()

CodePudding user response:

def cube(N)
    '''
    Return True if the sum of the cubes of the digits in N is equal
    to N, or False otherwise.

    N is assumed to be a string containing only decimal digits.
    '''

    total = 0

    # loop over each digit in N
    for c in N:
        # convert to an integer
        c = int(c)

        # cube c and add it to the total 
        total  = c ** 3

    if total == int(N):
        return True
    else:
        return False

Or, a more compact and Pythonic way to calculate the total:

total = sum(int(c) ** 3 for c in N)

CodePudding user response:

def sum_of_cubes(num):
    # Convert the number to a string
    num_str = str(num)

    # Initialize a variable to store the sum of the cubes
    sum = 0

    # Iterate over each character in the string
    for ch in num_str:
        # Convert the character to an integer
        digit = int(ch)

        # Calculate the cube of the digit
        cube = digit * digit * digit

        # Add the cube to the sum
        sum  = cube

    # Return the sum
    return sum

# Test the function with the example given in the prompt which is 215
result = sum_of_cubes(input("Enter a number: "))
print(result)  # Expected output: 134
  • Related