zoukankan      html  css  js  c++  java
  • [LeetCode#263]Factorial Trailing Zeroes

    Problem:

    Write a program to check whether a given number is an ugly number.

    Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

    Note that 1 is typically treated as an ugly number.

    Analysis:

    This problem is simple, but you may run into a complexty and easy-wrong way. 
    The below is a complex solution(wrong) try to use the same idea from "count primes".
    
    A complex and wrong solution:
    public class Solution {
        public boolean isUgly(int num) {
            if (num <= 0)
                return true;
                // throw new IllegalArgumentException("The passed in argument is not legal");
            if (num == 1)
                return true;
            boolean[] check_board = new boolean[num+1];
            Arrays.fill(check_board, true);
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (check_board[i] == true) {
                    for (int j = i*2; j <= num; j = j+i) {
                        check_board[j] = false;
                        if (j == num) {
                            if (!(i == 2 || i == 3 || i== 5)))
                                return true;
                        }
                    }
                }
            }
            return false;
        }
    }
    
    Why we so many uncessary computing and memeory reasource for a sigle number???
    (Something must be wrong for the solution)
    
    If a number is a ugly number, if must consist of (2, 3 5) through following way.
    num = (2^i) * (3^j) * (5^k) * 1
    
    Why not we strip out prime factor(2, 3, 5) one by one from num, then check if "num == 1"?
    How to strip out prime factor from a integer?
    Assume: a is the prime factor
    while (num % a == 0) {
        num = num / a;
    }
    Reason: since num could be fully divided by a (num % a == 0), we could still strip a from num. 
    This idea is very tricky compared with our past experience in using array. Take care!

    Solution:

    public class Solution {
        public boolean isUgly(int num) {
            if (num <= 0)
                return false;
            if (num == 1)
                return true;
            int[] x = {2, 3, 5};
            for (int a : x) {
                while (num % a == 0) {
                    num = num / a;
                }
            }
            return num == 1;
        }
    }
  • 相关阅读:
    致DBA:为什么你经常犯错,是因为你做的功课不够
    Hbase的shell命令学习
    mysql通过拷贝文件实现数据快速迁移实例
    项目领导力学习总结
    放权,从鞋柜开始
    不抱怨的世界
    定投我们自己
    mysql core文件的正确打开姿势
    2017小目标
    世界是有生命的(通向财富自由之路学习笔记十五)
  • 原文地址:https://www.cnblogs.com/airwindow/p/4774745.html
Copyright © 2011-2022 走看看