Example #1
0
void find_missing(unsigned n) {
    auto root = std::sqrt(2 * n);
    unsigned check = std::floor(root);
    unsigned sum = summation(check);

    if (sum > n) {
        std::cout << (sum - n) << " " << check << std::endl;
    } else {
        check = std::ceil(root);
        sum = summation(check);
        std::cout << (sum - n) << " " << check << std::endl;
    }
}
Example #2
0
int main(void)
{
    char choice;
    printf("Please press desired key to continue ... \n\n ");

    do
    {
        printf("\nMENU\n\n"
                " + : addition\n"
                " - : substraction\n "
                " * : multiplication\n "
                " / : division\n"
                " ^ : power\n"
                " q : quit\n\n");

        printf("Command: ");
        scanf(" %c ", &choice);

        switch(choice)
        {
            case '+': summation(); break;
            case '-': substraction(); break;
            case '*': multiplication(); break;
            case '/': division(); break;
            case '^': toThePower(); break;
            case 'q': break;

            default:
            {
                fprintf(stderr, "you didn't press expected key :(\n");
            }
         }
    }
    while (choice != 'q');
}
Example #3
0
int main(){
	float sum = summation(1.2, 1.3);
	printf("\n\nSum is: %f\n\n", sum);

	float diff = sub(1.5, 1.3);
	printf("\n\nDifferncet is: %f\n\n", diff);
}
Example #4
0
static PyObject* primes_sum(PyObject* self, PyObject* args){
    PyEval_InitThreads();
    Py_ssize_t start = 0, n = 0;
    uint64_t sum = 0;
    if (!PyArg_ParseTuple(args, "n|n:primes_sum", &start, &n)) return NULL;
    if (PyTuple_Size(args) == 1){
        n = start;
        start = 0;
    }
    if (n < 3 || start > n) return PyErr_Occurred() ? NULL : PyInt_FromLong(0);
    if (start < 2) start = 2;

    Py_BEGIN_ALLOW_THREADS  //----

    int threads = ParallelPrimeSieve::getMaxThreads();  // calls OpenMP's omp_get_max_threads
    ParallelPrimeSummation summation(threads);
    ParallelPrimeSieve pps;
    pps.setNumThreads(threads);
    pps.generatePrimes(start, n-1, &summation);

    for (uint64_t i = 0; i < summation.sums_list.size(); i += NO_FALSE_SHARING)
        sum += summation.sums_list[i];

    Py_END_ALLOW_THREADS    //----

    return Py_BuildValue("K", sum);
}
Example #5
0
double Vector<NTL::ZZ>::L2() const {
    NTL::ZZ summation(0);

    for (auto& e : *this) {
		summation += e * e;
    }
    return std::sqrt(std::exp(log(summation)));
}
double summation(double n)
{sum+=pow(n,3);
MO=sum;
    if(n>=1)
    return summation(n-1);
    else{sum=0;return MO;}

}
Example #7
0
double Vector<NTL::ZZX>::L2() const {
    NTL::ZZ summation(0);

    for (auto& e : *this) {
		if (e.rep.length() > 0) summation += e[0] * e[0];
    }
    return std::sqrt(std::exp(log(summation)));
}
 main()
{
    double num,i,j,m;
    while(scanf("%lf",&num)==1)
    {m=summation(num);
    printf("%.0lf\n",m);
    }
    return 0;
}
int main () {
    printf("iterative sum of squares from 1 to 10: %d\n",
            summation(square, 1, 10));
    printf("recursive gcd of 24 and 40: %d\n", gcd(24, 40));
    printf("recursive sum of squares from 1 to 10: %d\n",
            summation2(square, 1, 10));
    printf("iterative gcd of 24 and 40: %d\n", gcd2(24, 40));
    printf("tail-recursive gcd of 24 and 40: %d\n", gcd3(24, 40));
}
Example #10
0
int main(int argc, char const *argv[]) {
	int i = 2992;
	while(i < 10000) {
		if(summation(i) == i)
			printf("%d\n", i);
		i++;
	}
	return 0;
}
int main() {
    int v1[10] = {37, 5, 4, 8, 12, -10, 23, -20, 30, 35};
    int v2[10] = {-1, 0, 2, 3, 4, 7, 14, 28, 29, 50};
    std::cout << summation(6) << std::endl;
    std::cout << min(v1, 9) << std::endl;
    std::cout << sum(v1, 9) << std::endl;
    std::cout << isOrdered(v1, 9) << std::endl;
    std::cout << isOrdered(v2, 9) << std::endl;
    return 42;
}
int main () {

	int i = 0;
	int j = 0;
	int k = 0;
	int l = 0;

	for(k=0; k<3; k++) {
		for(l=0; l<3; l++) {
			U[k][l] = 0;
			if(k==l) {
					U[k][l] = 1;
			}

			L[k][k] = M[k][k] - summation(k,-1, 0);

			for(i=k+1;i<3;i++) {
				L[i][k] = M[i][k] - summation(k, i, 1);
			}

			for(j=k+1;j<3;j++) {
				U[k][j] = (M[k][j] - summation(k, j, 2)) / L[k][k];
			}
		}
	}

	printMatrix(U, 'M');
	printMatrix(U, 'U');
	printMatrix(L, 'L');

	y_1 = B[0] / L[0][0];
	y_2 = (B[1] - L[1][0] * y_1) / L[1][1];
	y_3 = (B[2] - (L[2][0] * y_1) - (L[2][1] * y_2)) / L[2][2];

	printf("y_1, y_2, y_3: %0.2f, %0.2f, %0.2f\n", y_1, y_2, y_3);

	x_3 = y_3;
	x_2 = y_2 - U[1][2] * x_3;
	x_1 = y_1 - U[0][1] * x_2 - U[0][2] * x_3;

	printf("x_1, x_2, x_3: %0.2f, %0.2f, %0.2f", x_1, x_2, x_3);
	return 0;
}
Example #13
0
int main(void)
{

    int *n;
    int *total = 0;
    void summation(int *number, int *sum);

    printf("Enter the number of elements = ");
    scanf("%i", &(*n) );

    summation( n, total );
    printf("total sum of %i elemts = %i", *n, *total );

}
Example #14
0
int* LUP-SOLVE(int L[][], int U[][],int Pi[],int b[], int rowsL) {
	

	int n=rowsL;
	int P[n][n], y[n], x[n];

	// Initialize P matrix
	for ( int i=0; i < n; i++) {
		for ( int j=0; j < n; j++) {
			if ( j == Pi[i])
				P[i][j] = 1;
			else
				P[i][j] = 0;
		}
	}
	// Calculate Pb from P and b
	for ( int i=0; i < n; i++) {
		for ( int j=0; j < n; j++) {
			Pb[i] += P[i][j]*b[j];
		}
	}

	// Initialize y and x
	for (int i=0; i < n; i++ )
		y[i] = 0,x[i] = 0;

	for(int i=1; i<n; i++)
		y[i] = Pb[i]- summation(L,y,1,i-1);

	for(int i=n;i>=0;i--) 
		x[i]=(y[i]-summation(U,x,i+1,n))/U[i][i];
	
	int *result = x;
	// returned a pointer to the array x.
	return result;	
}
Example #15
0
void benchmark(const EncryptedArray   & ea,
               const FHEPubKey        & pk,
               const FHESecKey        & sk,
               const MDL::Matrix<long>& data)
{
    const long BATCH_SIZE = 5000;
    MDL::Timer encTimer, evalTimer;
    MDL::EncVector mu(pk), sigma(pk);

    for (long part = 0; part *BATCH_SIZE < data.rows(); part++) {
        long from  = std::min<long>(part * BATCH_SIZE, data.rows());
        long to    = std::min<long>(from + BATCH_SIZE, data.rows());
        encTimer.start();
        auto ctxts = encrypt(data, pk, ea, from, to);
        encTimer.end();
        evalTimer.start();

        auto sum = summation(ctxts);
        mu    += sum.first;
        sigma += sum.second;
        evalTimer.end();
    }
    evalTimer.start();
    auto mu_mu = mu.covariance(ea, data.cols());
    NTL::ZZX N;
    std::vector<long> n(ea.size(), data.rows());
    ea.encode(N, n);
    sigma.multByConstant(N);
    for (size_t col = 0; col < data.cols(); col++) {
        ea.rotate(mu_mu[col], col * data.cols());
        sigma -= mu_mu[col];
    }
    evalTimer.end();

    MDL::Vector<long> mat;
    sigma.unpack(mat, sk, ea, true);
    for (int i = 0; i < data.cols(); i++) {
        for (int j = 0; j < data.cols(); j++) {
            std::cout << mat[i * data.cols() + j] << " ";
        }
        std::cout << std::endl;
    }
    printf("Covariance of %zd data, enc %f, eval %f\n", data.rows(),
           encTimer.second(), evalTimer.second());
}
Example #16
0
int setChannelIfOurs(int iofd, int chan, int val, int startaddr, int *pinsperchan, int nchan){
	int i, brkaddr, prevbrk;
	//Does this channel belong to us? If so, update!
	if(chan < startaddr){
		printf("channel %d belongs to a board at lower address.\n", chan);
		return -1;
	}
	prevbrk = startaddr;
	for(i=0; i<nchan; i++){
		brkaddr = summation(0,i, pinsperchan);
		if(chan >= prevbrk && chan < brkaddr){
			if(debug)
				fprintf(stderr,"Setting pin %d, global channel %d, local channel %d to %d\n", i, chan, chan-startaddr+prevbrk, val);  
			if(io_set_pwm(iofd, i, chan-startaddr+prevbrk, val) >= 0)
				return chan;
			else
				return -2;
			prevbrk=brkaddr;
		}
	}
	if(debug)
		fprintf(stderr,"channel %d belongs to a board at higher address.\n",chan);
	return -1;
}
int summation2(int_func f, int low, int high) {
    /* assume low <= high */
    if (low == high) return f(low);
    else return f(low) + summation(f, low+1, high);
}
Example #18
0
long long sumF(long long x){
	if(x==0) return 0;
	else if(x<10) return summation(x);
	else return sumF(x/10)+(x/10*45)+summation(x%10);
}
Example #19
0
int main()
{
    //float n2,n3,n4,n5;
   //while(scanf("%f%f%f%f", &n2, &n3, &n4, &n5) != EOF)
        printf( "%.2f\n", summation ( 5,5, 3, 3, 4, 5 ) );
}
Example #20
0
File: lab2.c Project: rcpenny/OSU
/*This program provide some elementray calculations for an unknown number
of simple data sets. (The number will be determined at runtime, based on
user input, but it is unknown at coding/compile time.) The data in each set
consists of a number of floating point values, but the number of values to be
entered for each data set will be input by the user.*/
int main(){

	int dataSetNum = 0;
	int optionNum = 0;
	int *ptr;
	float **data;
	int num = 0;
	float min = 0, max = 0, sum = 0, avg = 0;
	int index = 0;

	/* prompt for the number of data set */
	dataSetNum = prompt();

	ptr = calloc(dataSetNum, sizeof(int));
	data = calloc(dataSetNum, sizeof(float *));

	/* generate all data set */
	generate(dataSetNum, ptr, data);

	/* prompt for user options repeatedly */
	num = select();
	while (1){
		optionNum = option();
		switch (optionNum){
			case 1:
				min = minimum(data, num, ptr);
				printf("The minimum value in the data set is: %.2f\n", min);
			break;

			case 2:
				max = maximum(data, num, ptr);
				printf("The maximum value in the data set is: %.2f\n", max);
			break;

			case 3:
				sum = summation(data, num, ptr);
				printf("The sum of this data set is: %.2f\n", sum);
			break;

			case 4:
				sum = summation(data, num, ptr);
				avg = sum / *(ptr+num-1);
				printf("The average of this data set is %.2f\n", avg);
			break;

			case 5:
				bubbleSort(data, num, ptr);
				for(index = 0; index < *(ptr+num-1); index++){
					printf("%.2f\t", *(*(data+num-1)+index) );
				}
				printf("\n");
			break;

			case 6:
				num = select();
			break;

			case 7:
				exitProgram(data, ptr);
			break;

			default:
			break;
		}
	}

	return 0;
}
Example #21
0
int mainLoop (char *confpath) {
	cfg_t *cfg;
	redisContext *c;
	redisReply *reply;
	char *respcpy, *ascval, *curtok;
	unsigned int chan, val, start;
	int iofd, retval=-1, maxchain, numchan;
	int outbpc[3];
	/* Localize messages & types according to environment, since v2.9 */
	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "");

	/* Read configuration and initialize to default state*/
	statestr=malloc(sizeof(DEFSTATE)+1);
	strcpy(statestr,DEFSTATE);

	cfg = parse_conf(confpath == NULL ? "/etc/bone-shiftreg.conf" : confpath);
	if (!cfg) {
		fprintf(stderr,"Error parsing configuration file!\n");
		retval=-2;
		goto cleanupnone;
	}
	outbpc[0] = cfg_getint(cfg,"ser0-num-channels");
	outbpc[1] = cfg_getint(cfg,"ser1-num-channels");
	outbpc[2] = cfg_getint(cfg,"ser2-num-channels");
	if(cfg_getbool(cfg,"debug")){
		debug = 1;
	} else {
		debug = 0;
	}
	start = cfg_getint(cfg,"start-address");
	numchan = summation(0,NUMPINS-1, outbpc);
	printf("This board has a total of %d channels\n", numchan);

	/* Open remoteproc device */
	if((iofd = io_init(cfg_getstr(cfg,"pru-remoteproc-file"))) < 0){
		fprintf(stderr,"Failed to open remoteproc device file! Firmware still booting?\n");
		retval = -1;
		goto cleanupconf;
	}
	/* Set output channel count */
	maxchain = imax(imax(outbpc[0],outbpc[1]),outbpc[2]);
	if(maxchain == 0){
		fprintf(stderr,"At least one output chain must have more then zero channels!\n");
		goto cleanupio;
	}

	if(io_set_nchannels(iofd, maxchain) < 0){
		fprintf(stderr,"Failed to set max chain length to %d!\n", maxchain);
		retval = -2;
		goto cleanupio;
	}
	/* Establish Redis connection */
	printf("Connecting to redis at %s, port %ld\n", cfg_getstr(cfg,"redis-host"), cfg_getint(cfg,"redis-port"));
	c = redisConnect(cfg_getstr(cfg,"redis-host"), cfg_getint(cfg,"redis-port"));
	/* Handle Redis connection errors */
	if (c == NULL || c->err) {
		if (c) {
			fprintf(stderr,"Error: %s\n", c->errstr);
			goto cleanupall;
		} else {
			fprintf(stderr,"Can't allocate redis context\n");
			goto cleanupio;
		}
	}
	/* Authenticate if needed */
	if(cfg_getbool(cfg,"redis-authrequired")){
		const char authpref[] = "AUTH ";
		char *authstr = malloc(sizeof(authpref) + strlen(cfg_getstr(cfg,"redis-password")) + 1);
		memcpy(authstr, authpref, sizeof(authpref));
		strcat(authstr, cfg_getstr(cfg,"redis-password"));
		reply = redisCommand(c, authstr);
		free(authstr);
		if(!reply || reply->type == REDIS_REPLY_ERROR){
			fprintf(stderr,"authentication failed\n");
			goto cleanupall;
		}
		if(reply)
			freeReplyObject(reply);
	}
	reply = redisCommand(c, "PING");
	if(!reply || reply->type == REDIS_REPLY_ERROR){
		fprintf(stderr,"Unable to execute Redis commands, are you authenticated if necessary?\n");
		if(reply)
			freeReplyObject(reply);
		goto cleanupall;
	} else { 
		freeReplyObject(reply);
	}
	/* If we have gotten here we have initialized successfully */
	/* Restore state */ 
	if(cfg_getbool(cfg,"persistent-state")){
		if(restoreState(c, iofd, start, start+numchan, outbpc, NUMPINS) == -2){
			retval = -2;
			goto cleanupall;
		}
	}
	retval=0;
	/* Message handling loop */
	if(debug)
		fprintf(stderr,"Subscribed...\n");
	reply = redisCommand(c, "SUBSCRIBE changes");
	freeReplyObject(reply);
	while(redisGetReply(c,(void *)&reply) == REDIS_OK) {
		if(debug)
			fprintf(stderr,"Begin message parsing\n");
		// consume message
		if (reply == NULL) 
			continue;
		if (reply->type == REDIS_REPLY_ARRAY) {
			if(reply->elements == 3) {
				if(reply->element[0]->type == REDIS_REPLY_STRING && reply->element[2]->type == REDIS_REPLY_STRING && strcmp("message", reply->element[0]->str) == 0){
					if(debug)  
						fprintf(stderr,"Processing incoming message %s\n", reply->element[2]->str);
					//Message parsing
					respcpy = malloc(strlen(reply->element[2]->str)+1);
					assert(respcpy != NULL);
					strcpy(respcpy, reply->element[2]->str);
					#ifdef ALLOWSHUTDOWN
					if(strstr(respcpy, "@")){
						free(respcpy);
						freeReplyObject(reply);
						retval = -3;
						goto cleanupall;
					}
					#endif
					if(strstr(respcpy, "!")){
						//Reload requested, cleanup and return 0 (which causes a reload)
						free(respcpy);
						freeReplyObject(reply);
						goto cleanupall;
					}
					curtok = strtok(respcpy,",");
					while(curtok != NULL){
						ascval = strsep(&curtok, ":");
						if(curtok != NULL){
							chan = atoi(ascval);
							val = atoi(curtok);
							//Does this channel belong to us? If so, update!
							if(setChannelIfOurs(iofd, chan, val, start, outbpc, NUMPINS) == -2){
								/* IO error, bail out! */
								fprintf(stderr, "IO error, bailing!\n");
								freeReplyObject(reply);
								free(respcpy);
								goto cleanupall;
							}
						} else {
							fprintf(stderr, "Malformed message published to channel!\n");
						}
						curtok = strtok(NULL,",");
					}
					free(respcpy);
				}
			} else {
				fprintf(stderr, "Invalid number of elements in reply array!\n");
			}
		}
		freeReplyObject(reply);
	}
	fprintf(stderr, "Lost connection to redis server!\n");
cleanupall:
	redisFree(c);
cleanupio:
	io_close(iofd);
cleanupconf:
	cfg_free(cfg);
cleanupnone:
	free(statestr);
	return retval;
}
Example #22
0
void main()
{
    printf("%lld", (long long)pow(summation(100), 2) - summation_pow(100, 2));
}
int summation(int N) {
    if(N==1) return 1;
    return N+summation(N-1);
}
Example #24
0
int main(void){
   std::cout << summation() << std::endl;

   return 0;
}