Skip to content

Instantly share code, notes, and snippets.

@roxtar
Created December 6, 2010 21:44
Show Gist options
  • Save roxtar/731021 to your computer and use it in GitHub Desktop.
Save roxtar/731021 to your computer and use it in GitHub Desktop.
Program to find prime factors of a number
/* This program is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation, either version 3 of the License, or */
/* (at your option) any later version. */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Description: Program to find prime factors of a number */
/* Author: Rohit Krishna Kumar */
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node * next;
};
struct Node * factors(int n)
{
int i;
struct Node * node = (struct Node *)malloc(sizeof(struct Node));
for(i = 2; i*i <= n; i++)
{
if(!(n % i))
{
node->data = i;
node->next = factors(n/i);
return node;
}
}
node->data = n;
node->next = 0;
return node;
}
void print_nodes(struct Node *n)
{
while(n)
{
printf("%d\n", n->data);
n = n->next;
}
}
void free_nodes(struct Node *n)
{
while(n)
{
struct Node *next = n->next;
free(n);
n = next;
}
}
int main()
{
struct Node *n = factors(2256);
print_nodes(n);
free_nodes(n);
return 1;
}
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Description: Program to find prime factors of a number
# Author: Rohit Krishna Kumar
def factors(n):
i = 2
while((i * i) <= n):
if((n % i) == 0):
return [i] + factors(n/i)
i+=1
return [n]
print factors(2256)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment