How find prime factors of a given number using C++

C, C++, Visual C++, C++.Net Topics
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: How find prime factors of a given number using C++

Post by Neo » Tue Apr 27, 2010 5:31 am

There were some syntax & logical errors. However your effort on this made me do the correction for you ;)

Code: Select all

#include <stdio.h>
#include <stdlib.h>

typedef struct primes_ {
	int no;
	struct primes_ * next;
} PrimesList;


void main (){

	int i, B = 1024, count, flag1;
	PrimesList *list, *temp, *initial;

	list = (PrimesList*)malloc(sizeof(PrimesList));
	list->no = 2;
	list->next = NULL;
	temp = list;

	count = 1;

	i = 3;

	while (i <= B) {

		initial = list;
		flag1 = 0;

		while ( ((initial->next) != NULL) && (flag1 == 0) ) {
			if ((i % initial->no) == 0){
				flag1 = 1; // prime factor exists -> skip this number
			}
			else{
				initial = initial->next; // advance to next prime
			}
		}

		if (flag1 == 0) {
			temp->next = (PrimesList*)malloc(sizeof(PrimesList));
			temp = temp->next;
			temp->no = i;
			temp->next = NULL;
			count++;
		}
		i += 2;
	}

	temp = list;

	while (temp != NULL) {
		printf("%d next: \n ",temp->no);
		temp = temp->next;
	}
	printf("\ntotal: %d\n",count);

	system("pause");
	//getchar();
}
ghostrider_gr
Sergeant
Sergeant
Posts: 17
Joined: Mon Apr 19, 2010 1:01 am

Re: How find prime factors of a given number using C++

Post by ghostrider_gr » Tue Apr 27, 2010 1:04 pm

Neo wrote:There were some syntax & logical errors. However your effort on this made me do the correction for you ;)

Code: Select all

#include <stdio.h>
#include <stdlib.h>

typedef struct primes_ {
	int no;
	struct primes_ * next;
} PrimesList;


void main (){

	int i, B = 1024, count, flag1;
	PrimesList *list, *temp, *initial;

	list = (PrimesList*)malloc(sizeof(PrimesList));
	list->no = 2;
	list->next = NULL;
	temp = list;

	count = 1;

	i = 3;

	while (i <= B) {

		initial = list;
		flag1 = 0;

		while ( ((initial->next) != NULL) && (flag1 == 0) ) {
			if ((i % initial->no) == 0){
				flag1 = 1; // prime factor exists -> skip this number
			}
			else{
				initial = initial->next; // advance to next prime
			}
		}

		if (flag1 == 0) {
			temp->next = (PrimesList*)malloc(sizeof(PrimesList));
			temp = temp->next;
			temp->no = i;
			temp->next = NULL;
			count++;
		}
		i += 2;
	}

	temp = list;

	while (temp != NULL) {
		printf("%d next: \n ",temp->no);
		temp = temp->next;
	}
	printf("\ntotal: %d\n",count);

	system("pause");
	//getchar();
}
you saved my life... thanksssss :D
Post Reply

Return to “C/C++ Programming”