码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode#263]Factorial Trailing Zeroes

时间:2015-09-01 06:57:10      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

[LeetCode#263]Factorial Trailing Zeroes

标签:

原文地址:http://www.cnblogs.com/airwindow/p/4774745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!