合数分解.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. // 函数:判断一个数是否为素数
  4. int is_prime(int num) {
  5. int i;
  6. if (num <= 1) return 0;
  7. if (num == 2) return 1;
  8. if (num % 2 == 0) return 0;
  9. for (i = 3; i * i <= num; i += 2) {
  10. if (num % i == 0) return 0;
  11. }
  12. return 1;
  13. }
  14. // 函数:获取一个数的所有素数因子
  15. void get_prime_factors(int num, int *factors, int *count) {
  16. int factor = 2;
  17. while (num > 1) {
  18. if (num % factor == 0) {
  19. factors[*count] = factor;
  20. (*count)++;
  21. num /= factor;
  22. } else {
  23. factor++;
  24. while (!is_prime(factor)) {
  25. factor++;
  26. }
  27. }
  28. }
  29. }
  30. int main() {
  31. int i,j;
  32. int num;
  33. scanf("%d", &num);
  34. if (num <= 1) {
  35. printf("输入的数必须大于1且为合数。\n");
  36. return 1;
  37. }
  38. int factors[32]; // 假设最大int的素数因子数量不会超过32个
  39. int count = 0;
  40. get_prime_factors(num, factors, &count);
  41. int occurrences[32] = {0}; // 用于记录每个素数因子的出现次数
  42. int unique_factors[32]; // 记录所有唯一的素数因子
  43. int unique_count = 0;
  44. for (i = 0; i < count; i++) {
  45. int factor = factors[i];
  46. int found = 0;
  47. for (j = 0; j < unique_count; j++) {
  48. if (unique_factors[j] == factor) {
  49. occurrences[j]++;
  50. found = 1;
  51. break;
  52. }
  53. }
  54. if (!found) {
  55. unique_factors[unique_count] = factor;
  56. occurrences[unique_count] = 1;
  57. unique_count++;
  58. }
  59. }
  60. // 输出只出现一次的素数因子
  61. for (i = 0; i < unique_count; i++) {
  62. if (occurrences[i] == 1) {
  63. printf("%d ", unique_factors[i]);
  64. }
  65. }
  66. printf("\n");
  67. return 0;
  68. }