#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
int square(int a){
return a * a;
}
void prime_factors(int n){
// this is an array of n elements, which will contain all found primes.
// curprime stores the index of the last found prime, which saves us searching for where to insert the next one and things.
int* primes = calloc(sizeof(int), n);
int curprime = 0;
printf("1:\n"); // Micro optimization, and rids me of the messing around that is 1.
for(int i=2; i<=n; i++){
// Print the current i.
printf("%i: ",i);
// Define val, which we'll slowly make smaller and smaller. Mwahaha.
int val = i;
int isprime = true; // This will be set to false if it's divisible by any primes, which of course, means it's also not a prime.
// Loop through primes, this loop stops if we've reached either more than sqrt(count) primes, or val is equal to zero (as such, it's fully prime factorized).
for(int*prime_pointer = primes; val && square((int)(prime_pointer-primes)) < curprime; prime_pointer++){
int prime = *prime_pointer;
// if the current val is divisible by the current prime.
while(val%prime == 0){
isprime = false; // We know that this number isn't prime.
val = val / prime; // Divide val by it.
printf("%i ",prime);// And write this prime.
}
}
if(isprime){ // If this number is a prime.
printf("%i ",i); // Append it to its own list.
primes[curprime++] = i; // And append this new prime to our list of primes.
}
printf("\n"); // Terminate the line with a newline. Duh...
}
}
int main(int argc, char** argv){
prime_factors(1000);
}
prime_factors
整数n
を受け取り、printfを介して次の形式で出力する関数を定義します。
1:
2: 2
3: 3
4: 2 2
5: 5
6: 2 3
7: 7
8: 2 2 2
9: 3 3
10: 2
これはO(n)の追加メモリを使用し、時間の複雑さはわかりません。
オンラインでお試しください!