December 14, 2015
On Sunday, 13 December 2015 at 01:01:07 UTC, cym13 wrote:

> That's because you want to modify it in product passing it by ref.

Hmm, that seems different to c++.


On Sunday, 13 December 2015 at 11:37:50 UTC, cym13 wrote:

>
> As cryptic as it is this means that the range you passed to reduce is empty. Reduce needs it not to be because as I said it needs a seed and as you didn't pass one explicitely as argument it tries to take the first element of the range (and fails obviously). You can either pass it a seed explicitely or add a non-empty check before the return.


Here is the full code, where I changed the product function. Sorry, I don't understand what the difference now and why it crashes.

import std.stdio, std.array, std.algorithm;


int product(const ref int[] arr){

	/*int p = 1;
	foreach(i;arr)
		p*=i;
 	return p;*/
 	
 	return arr.reduce!((a, b) => a*b)();

}


int [] prim_sieve(int n){

	bool [] T;
	T.length = n;
	T[0] = true;
	T[1] = true;
	
	for(int i = 2; i*i <= T.length-1;++i){
		for(int j = i*i;j<T.length; j+=i)
			T[j] =true;
	}
	int[] v;
	foreach(int i,t;T)
		if(t==false)
			v~=i;
	return v;
}

int[] prim_factors(int n, const ref int[] P){
	
	int[] v;
	
	for(int i; P[i]*P[i]<=n;++i){
		while(n%P[i]==0){
			v~=P[i];
			n/=P[i];
		}
	}
	if(n>1)
		v~=n;
		
	return v.dup.sort.uniq.array;

}


void bubblesort(ref int[2][] v){

	size_t n = v.length;
	do{
		int newn = 1;
		for(int i = 0;i<n-1; ++i){
			if(v[i][1]>v[i+1][1]){
				auto temp = v[i];
				v[i] = v[i+1];
				v[i+1] = temp;
				newn = i+1;
			}
		}
		n=newn;	
	}
	while(n>1);
}



void main(){
	
	int[] P = prim_sieve(500);
	
	int[2][] v;
	
	foreach(k;1..100001){
		auto t = prim_factors(k,P);
		v~= [k,product(t)];
	}
	
	bubblesort(v);
	
	writeln(v[9999][0]);
}
December 14, 2015
On Monday, 14 December 2015 at 11:45:50 UTC, Namal wrote:
> 	
> 	foreach(k;1..100001){
> 		auto t = prim_factors(k,P);
>   		v~= [k,product(t)];
> 	}

it crashes because your first t in the loop is an empty array

because 1 is not a prime ( in "prim_sieve" : T[1] = true)
later when you loop starting with k = 1, prim_factors(1,P) gives you back an empty array.
so either loop through 2..100001 or guard against the empty array
if (!t.empty) v~= [k, product(t)];

i don't think you need any ref in your functions parameters, as a slice is already a reference
http://dlang.org/spec/arrays.html#slicing
1 2
Next ›   Last »