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


    1.欧几里得算法

    思路:欧几里得算法

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

    1. class Solution {
    2. public int findGCD(int[] nums) {
    3. int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    4. for (int num : nums) {
    5. if (num > max) {
    6. max = num;
    7. }
    8. if (num < min) {
    9. min = num;
    10. }
    11. }
    12. return gcd(max,min);
    13. }
    14. public int gcd(int a, int b) {
    15. return b == 0 ? a : gcd(b,a%b);
    16. }
    17. }

    2.素数和合数

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

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

    1)计数质数

    思路:第一种循环暴力

    1. class Solution {
    2. public int countPrimes(int n) {
    3. int count = 0;
    4. if(n>2){
    5. count++;
    6. }else{
    7. return 0;
    8. }
    9. for(int i = 3;i
    10. if(isPrime(i)){
    11. count++;
    12. }
    13. }
    14. return count;
    15. }
    16. public boolean isPrime(int n){
    17. double N = Math.sqrt(n);
    18. for(int i = 2;i<=N;i++){
    19. if(n%i == 0){
    20. return false;
    21. }
    22. }
    23. return true;
    24. }
    25. }

    2)埃氏筛

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

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

    1. class Solution {
    2. public int countPrimes(int n) {
    3. int count = 0;
    4. int[] nums = new int[n];
    5. for(int i = 2;i
    6. if(nums[i] == 0){
    7. count++;
    8. if((long) i*i
    9. for(int j = i*i;j
    10. nums[j] = 1;
    11. }
    12. }
    13. }
    14. }
    15. return count;
    16. }
    17. }

    3.丑数

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

    1. class Solution {
    2. public boolean isUgly(int n) {
    3. if(n == 0){
    4. return false;
    5. }
    6. int[] elements = {2,3,5};
    7. for(int e : elements){
    8. while(n%e == 0){
    9. n = n/e;
    10. }
    11. }
    12. if(n == 1){
    13. return true;
    14. }else{
    15. return false;
    16. }
    17. }
    18. }

  • 相关阅读:
    嵌入式Linux运行一定需要MMU吗
    《C和指针》笔记29:数组名和指针
    超分辨率技术在实时音视频领域的研究与实践
    LazySnapping算法详解
    word模板内容替换
    [附源码]java毕业设计网吧购物系统
    集合数据丢失distinct与EqualsAndHashCode的Bug问题
    毕设 JAVA.JSP花店管理系统
    macOS 安装brew和ffmpeg
    Fast DDS之Subscriber
  • 原文地址:https://blog.csdn.net/Candy___i/article/details/132888237