Codility-CommonPrimeDivisors
来源:互联网 发布:工资发放软件 编辑:程序博客网 时间:2024/05/14 05:30
A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.
A prime D is called a prime divisor of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20.
You are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same.
For example, given:
- N = 15 and M = 75, the prime divisors are the same: {3, 5};
- N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5};
- N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}.
Write a function:
int solution(vector<int> &A, vector<int> &B);
that, given two non-empty zero-indexed arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same.
For example, given:
A[0] = 15 B[0] = 75 A[1] = 10 B[1] = 30 A[2] = 3 B[2] = 5
the function should return 1, because only one pair (15, 75) has the same set of prime divisors.
Assume that:
- Z is an integer within the range [1..6,000];
- each element of arrays A, B is an integer within the range [1..2147483647].
Complexity:
- expected worst-case time complexity is O(Z*log(max(A)+max(B))2);
- expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
思路:a和b共有质因子必然全都是a和b最大公约数gcd(a,b)的因子。若a和b有完全相同的质因子集,则a和b所有的质因子都是gcd(a,b)的质因子,让a不断除以gcd(a,b)的每一个质因子后(如b=75,gcd(a,b)=15,gcd(a,b)的质因子为3和5,b=b/3=25,b=b/5=5,b=b/5=1),最终会得到1,对b也是如此。故最终若a=b=1,则a和b有相同的质因子集,否则没有。
代码:
- Codility-CommonPrimeDivisors
- codility CommonPrimeDivisors
- codility
- codility
- Codility -- Fish
- Codility -- Brackets
- Codility -- grocery_store
- Codility -- Triangle
- [codility]Triangle
- [codility]Brackets
- [codility]Fish
- [codility]Dominator
- [codility]Equi
- [codility]equi
- [codility]MinAbsSumOfTwo
- [codility]CountMultiplicativePairs
- 【Codility】PassingCars
- [codility]MinMaxDivision
- STL系列之四 heap 堆
- struts用法
- 给你一个由n-1个整数组成的未排序的序列,其元素都是1到n中的不同的整数。请写出一个寻找序列中缺失整数的线性时间算法。
- java中使用堆外内存,关于内存回收需要注意的事和没有解决的遗留问题(等大神解答)
- js自定义对象、属性、方法(转)
- Codility-CommonPrimeDivisors
- Photoshop制作Android UI:如何从大图片中准确剪切出圆角正方形 图片
- 高斯二维滤波
- Sudoku Solver
- 面向对象程序设计上机练习七(类和对象)
- java过滤字符串中的emoji表情
- 枚举类型的单例模式(java)
- 最大团
- IE8 文件上传文件为空的问题