【程序14】 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。

来源:互联网 发布:淘宝网店铺搜索 编辑:程序博客网 时间:2024/05/18 02:07

方法一:直接搞吧,查找素数,整除就出,否则继续查找知道带求数字变为1。


#include <stdio.h>int map[100000];int main(){int i,j,k,n;map[0] = map[1] = 1;for(i=2;i<100000;++i)for(j=i+i;j<100000;j+=i)map[j]++;while(~scanf("%d",&n),n>1){i=2;printf("%d=",n); while(map[n]){while(map[i] || (n%i!=0))++i;n /= i;printf("%d*",i);}printf("%d\n",n);}return 0;}


方法二:


挂个链表,查找省力了,但是内存开的痛苦,反而降低了效率。

#include <stdio.h>#include <stdlib.h>#include <time.h>typedef struct node node;struct node{int value;node *next;};node map[100000];int main(){int i,j,n;node *temp = NULL;clock_t t = clock(); for(i=2;i<100000;++i)for(j=i+i;j<100000;j+=i){temp = (node*)malloc(sizeof(node));temp->value = i;temp->next = map[j].next;map[j].next = temp;}printf("time = %ld\n",clock() - t);while(~scanf("%d",&n),n>1){temp = map[n].next;printf("%d=",n); while(temp){if(map[temp->value].next == NULL){while(n%temp->value == 0){if(n/temp->value != 1)printf("%d*",temp->value);else printf("%d",temp->value);n /= temp->value;}}temp = temp->next;}if(n>1)printf("%d",n);printf("\n");}return 0;}


方法三:


换成静态分配内存,速度好了一些。

#include <stdio.h>#include <stdlib.h>#include <time.h>typedef struct node node;struct node{int value;node *next;};node map[100000];node mem[1000000];int mem_top = 0; int main(){int i,j,n;node *temp = NULL;clock_t t = clock();for(i=2;i<100000;++i)for(j=i+i;j<100000;j+=i){temp = &mem[mem_top++];temp->value = i;temp->next = map[j].next;map[j].next = temp;}printf("time = %ld\n",clock() - t);while(~scanf("%d",&n),n>1){temp = map[n].next;printf("%d=",n);while(temp){if(map[temp->value].next == NULL){while(n%temp->value == 0){if(n/temp->value != 1)printf("%d*",temp->value);else printf("%d",temp->value);n /= temp->value;}}temp = temp->next;}if(n>1)printf("%d",n);printf("\n");}return 0;}



原创粉丝点击