算法通关村第13关【黄金】| 数论问题

1.欧几里得算法

思路:欧几里得算法

【欧几里得演算法(辗转相除法)】 https://www.bilibili.com/video/BV19r4y127fu/?share_source=copy_web\&vd_source=d124eda224bf54d0e3ab795c0b89dbb0

java 复制代码
class Solution {
    public int findGCD(int[] nums) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        for (int num : nums) {
            if (num > max) {
                max = num;
            }
            if (num < min) {
                min = num;
            }
        }
        return gcd(max,min);

    }

    public int gcd(int a, int b) {
        return b == 0 ? a : gcd(b,a%b);
    }
}

2.素数和合数

素数是指2开始,除了1和它本身之外没有能整除它的数

合数是指2开始,除了1和它本身之外有能整除它的数

1)计数质数

思路:第一种循环暴力

java 复制代码
class Solution {
    public int countPrimes(int n) {
        int count = 0;
        if(n>2){
            count++;
        }else{
            return 0;
        }
        for(int i = 3;i<n;i++){
            if(isPrime(i)){
                count++;
            }
        }
        return count;
    }

    public boolean isPrime(int n){
        double N = Math.sqrt(n);
        for(int i = 2;i<=N;i++){
            if(n%i == 0){
                return false;
            }
        }
        return true;
    }
}

2)埃氏筛

当确定一个数为素数则它的n倍数都不是素数

注意的是每次筛选从i*i开始,因为这是最小的未被筛选过的,例如3开始筛选3的1,2,3,4,5...倍数都被筛选过了,那么5开始筛选就得从5*5开始

java 复制代码
class Solution {
    public int countPrimes(int n) {
        int count = 0;
        int[] nums = new int[n];
        for(int i = 2;i<n;i++){
            if(nums[i] == 0){
                count++;
                if((long) i*i<n){
                    for(int j = i*i;j<n;j += i){
                        nums[j] = 1;
                    }
                }                
            }
        }
        return count;
    }
}

3.丑数

思路:可以知道一个数是丑数那么,n = 2^a+3^b+5^c成立

java 复制代码
class Solution {
    public boolean isUgly(int n) {
      if(n == 0){
        return false;
      }
      int[] elements = {2,3,5};
      for(int e : elements){
        while(n%e == 0){
          n = n/e;
        }
      }
      if(n == 1){
        return true;
      }else{
        return false;
      }
    }
}
相关推荐
Mephisto.java24 分钟前
【力扣 | SQL题 | 每日四题】力扣2082, 2084, 2072, 2112, 180
sql·算法·leetcode
robin_suli25 分钟前
滑动窗口->dd爱框框
算法
丶Darling.27 分钟前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
labuladuo52037 分钟前
Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
数据结构·c++·算法
Indigo_code1 小时前
【数据结构】【链表代码】合并有序链表
数据结构·windows·链表
jiyisuifeng19911 小时前
代码随想录训练营第54天|单调栈+双指针
数据结构·算法
我言秋日胜春朝★1 小时前
【C++】红黑树
数据结构
꧁༺❀氯ྀൢ躅ྀൢ❀༻꧂1 小时前
实验4 循环结构
c语言·算法·基础题
新晓·故知1 小时前
<基于递归实现线索二叉树的构造及遍历算法探讨>
数据结构·经验分享·笔记·算法·链表
总裁余(余登武)2 小时前
算法竞赛(Python)-万变中的不变“随机算法”
开发语言·python·算法