Search Results

Search found 425 results on 17 pages for 'prime'.

Page 5/17 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Threading across multiple files

    - by Zach M.
    My program is reading in files and using thread to compute the highest prime number, when I put a print statement into the getNum() function my numbers are printing out. However, it seems to just lag no matter how many threads I input. Each file has 1 million integers in it. Does anyone see something apparently wrong with my code? Basically the code is giving each thread 1000 integers to check before assigning a new thread. I am still a C noobie and am just learning the ropes of threading. My code is a mess right now because I have been switching things around constantly. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <pthread.h> #include <math.h> #include <semaphore.h> //Global variable declaration char *file1 = "primes1.txt"; char *file2 = "primes2.txt"; char *file3 = "primes3.txt"; char *file4 = "primes4.txt"; char *file5 = "primes5.txt"; char *file6 = "primes6.txt"; char *file7 = "primes7.txt"; char *file8 = "primes8.txt"; char *file9 = "primes9.txt"; char *file10 = "primes10.txt"; char **fn; //file name variable int numberOfThreads; int *highestPrime = NULL; int fileArrayNum = 0; int loop = 0; int currentFile = 0; sem_t semAccess; sem_t semAssign; int prime(int n)//check for prime number, return 1 for prime 0 for nonprime { int i; for(i = 2; i <= sqrt(n); i++) if(n % i == 0) return(0); return(1); } int getNum(FILE* file) { int number; char* tempS = malloc(20 *sizeof(char)); fgets(tempS, 20, file); tempS[strlen(tempS)-1] = '\0'; number = atoi(tempS); free(tempS);//free memory for later call return(number); } void* findPrimality(void *threadnum) //main thread function to find primes { int tNum = (int)threadnum; int checkNum; char *inUseFile = NULL; int x=1; FILE* file; while(currentFile < 10){ if(inUseFile == NULL){//inUseFIle being used to check if a file is still being read sem_wait(&semAccess);//critical section inUseFile = fn[currentFile]; sem_post(&semAssign); file = fopen(inUseFile, "r"); while(!feof(file)){ if(x % 1000 == 0 && tNum !=1){ //go for 1000 integers and then wait sem_wait(&semAssign); } checkNum = getNum(file); /* * * * * I think the issue is here * * * */ if(checkNum > highestPrime[tNum]){ if(prime(checkNum)){ highestPrime[tNum] = checkNum; } } x++; } fclose(file); inUseFile = NULL; } currentFile++; } } int main(int argc, char* argv[]) { if(argc != 2){ //checks for number of arguements being passed printf("To many ARGS\n"); return(-1); } else{//Sets thread cound to user input checking for correct number of threads numberOfThreads = atoi(argv[1]); if(numberOfThreads < 1 || numberOfThreads > 10){ printf("To many threads entered\n"); return(-1); } time_t preTime, postTime; //creating time variables int i; fn = malloc(10 * sizeof(char*)); //create file array and initialize fn[0] = file1; fn[1] = file2; fn[2] = file3; fn[3] = file4; fn[4] = file5; fn[5] = file6; fn[6] = file7; fn[7] = file8; fn[8] = file9; fn[9] = file10; sem_init(&semAccess, 0, 1); //initialize semaphores sem_init(&semAssign, 0, numberOfThreads); highestPrime = malloc(numberOfThreads * sizeof(int)); //create an array to store each threads highest number for(loop = 0; loop < numberOfThreads; loop++){//set initial values to 0 highestPrime[loop] = 0; } pthread_t calculationThread[numberOfThreads]; //thread to do the work preTime = time(NULL); //start the clock for(i = 0; i < numberOfThreads; i++){ pthread_create(&calculationThread[i], NULL, findPrimality, (void *)i); } for(i = 0; i < numberOfThreads; i++){ pthread_join(calculationThread[i], NULL); } for(i = 0; i < numberOfThreads; i++){ printf("this is a prime number: %d \n", highestPrime[i]); } postTime= time(NULL); printf("Wall time: %ld seconds\n", (long)(postTime - preTime)); } } Yes I am trying to find the highest number over all. So I have made some head way the last few hours, rescucturing the program as spudd said, currently I am getting a segmentation fault due to my use of structures, I am trying to save the largest individual primes in the struct while giving them the right indices. This is the revised code. So in short what the first thread is doing is creating all the threads and giving them access points to a very large integer array which they will go through and find prime numbers, I want to implement semaphores around the while loop so that while they are executing every 2000 lines or the end they update a global prime number. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <pthread.h> #include <math.h> #include <semaphore.h> //Global variable declaration char *file1 = "primes1.txt"; char *file2 = "primes2.txt"; char *file3 = "primes3.txt"; char *file4 = "primes4.txt"; char *file5 = "primes5.txt"; char *file6 = "primes6.txt"; char *file7 = "primes7.txt"; char *file8 = "primes8.txt"; char *file9 = "primes9.txt"; char *file10 = "primes10.txt"; int numberOfThreads; int entries[10000000]; int entryIndex = 0; int fileCount = 0; char** fileName; int largestPrimeNumber = 0; //Register functions int prime(int n); int getNum(FILE* file); void* findPrimality(void *threadNum); void* assign(void *num); typedef struct package{ int largestPrime; int startingIndex; int numberCount; }pack; //Beging main code block int main(int argc, char* argv[]) { if(argc != 2){ //checks for number of arguements being passed printf("To many threads!!\n"); return(-1); } else{ //Sets thread cound to user input checking for correct number of threads numberOfThreads = atoi(argv[1]); if(numberOfThreads < 1 || numberOfThreads > 10){ printf("To many threads entered\n"); return(-1); } int threadPointer[numberOfThreads]; //Pointer array to point to entries time_t preTime, postTime; //creating time variables int i; fileName = malloc(10 * sizeof(char*)); //create file array and initialize fileName[0] = file1; fileName[1] = file2; fileName[2] = file3; fileName[3] = file4; fileName[4] = file5; fileName[5] = file6; fileName[6] = file7; fileName[7] = file8; fileName[8] = file9; fileName[9] = file10; FILE* filereader; int currentNum; for(i = 0; i < 10; i++){ filereader = fopen(fileName[i], "r"); while(!feof(filereader)){ char* tempString = malloc(20 *sizeof(char)); fgets(tempString, 20, filereader); tempString[strlen(tempString)-1] = '\0'; entries[entryIndex] = atoi(tempString); entryIndex++; free(tempString); } } //sem_init(&semAccess, 0, 1); //initialize semaphores //sem_init(&semAssign, 0, numberOfThreads); time_t tPre, tPost; pthread_t coordinate; tPre = time(NULL); pthread_create(&coordinate, NULL, assign, (void**)numberOfThreads); pthread_join(coordinate, NULL); tPost = time(NULL); } } void* findPrime(void* pack_array) { pack* currentPack= pack_array; int lp = currentPack->largestPrime; int si = currentPack->startingIndex; int nc = currentPack->numberCount; int i; int j = 0; for(i = si; i < nc; i++){ while(j < 2000 || i == (nc-1)){ if(prime(entries[i])){ if(entries[i] > lp) lp = entries[i]; } j++; } } return (void*)currentPack; } void* assign(void* num) { int y = (int)num; int i; int count = 10000000/y; int finalCount = count + (10000000%y); int sIndex = 0; pack pack_array[(int)num]; pthread_t workers[numberOfThreads]; //thread to do the workers for(i = 0; i < y; i++){ if(i == (y-1)){ pack_array[i].largestPrime = 0; pack_array[i].startingIndex = sIndex; pack_array[i].numberCount = finalCount; } pack_array[i].largestPrime = 0; pack_array[i].startingIndex = sIndex; pack_array[i].numberCount = count; pthread_create(&workers[i], NULL, findPrime, (void *)&pack_array[i]); sIndex += count; } for(i = 0; i< y; i++) pthread_join(workers[i], NULL); } //Functions int prime(int n)//check for prime number, return 1 for prime 0 for nonprime { int i; for(i = 2; i <= sqrt(n); i++) if(n % i == 0) return(0); return(1); }

    Read the article

  • Are there any working implementations of the rolling hash function used in the Rabin-Karp string sea

    - by c14ppy
    I'm looking to use a rolling hash function so I can take hashes of n-grams of a very large string. For example: "stackoverflow", broken up into 5 grams would be: "stack", "tacko", "ackov", "ckove", "kover", "overf", "verfl", "erflo", "rflow" This is ideal for a rolling hash function because after I calculate the first n-gram hash, the following ones are relatively cheap to calculate because I simply have to drop the first letter of the first hash and add the new last letter of the second hash. I know that in general this hash function is generated as: H = c1ak - 1 + c2ak - 2 + c3ak - 3 + ... + cka0 where a is a constant and c1,...,ck are the input characters. If you follow this link on the Rabin-Karp string search algorithm , it states that "a" is usually some large prime. I want my hashes to be stored in 32 bit integers, so how large of a prime should "a" be, such that I don't overflow my integer? Does there exist an existing implementation of this hash function somewhere that I could already use? Here is an implementation I created: public class hash2 { public int prime = 101; public int hash(String text) { int hash = 0; for(int i = 0; i < text.length(); i++) { char c = text.charAt(i); hash += c * (int) (Math.pow(prime, text.length() - 1 - i)); } return hash; } public int rollHash(int previousHash, String previousText, String currentText) { char firstChar = previousText.charAt(0); char lastChar = currentText.charAt(currentText.length() - 1); int firstCharHash = firstChar * (int) (Math.pow(prime, previousText.length() - 1)); int hash = (previousHash - firstCharHash) * prime + lastChar; return hash; } public static void main(String[] args) { hash2 hashify = new hash2(); int firstHash = hashify.hash("mydog"); System.out.println(firstHash); System.out.println(hashify.hash("ydogr")); System.out.println(hashify.rollHash(firstHash, "mydog", "ydogr")); } } I'm using 101 as my prime. Does it matter if my hashes will overflow? I think this is desirable but I'm not sure. Does this seem like the right way to go about this?

    Read the article

  • Excel: Conditional Formatting (Highlighting) Values Based on Another Worksheet

    - by ScottSEA
    I have a workbook that has two worksheets. The first worksheet is simply a list of the first 78,498 prime numbers in a single column, A1-A78498. The second worksheet has a grid of numbers from 1 to n. The goal is to highlight the cells with prime numbers in the grid by referencing the prime number values in the other worksheet. Is this possible, and if so, how? edit I have named the column with my prime numbers "PRIMES1T". I would like the formula to work for the entire worksheet, regardless of size, but my excel-fu is extremely weak. If at all possible, I would like to be able to enter the formula in the dialog box for conditional formatting (as below): I have tried =NOT(ISNA(MATCH(A:Z,PRIMES1T,0) (only A-Z, but have to start somewhere) with no luck.

    Read the article

  • Improving python code

    - by cobie
    I just answered the question on project euler about finding circular primes below 1 million using python. My solution is below. I was able to reduce the running time of the solution from 9 seconds to about 3 seconds. I would like to see what else can be done to the code to reduce its running time further. This is strictly for educational purposes and for fun. import math import time def getPrimes(n): """returns set of all primes below n""" non_primes = [j for j in range(4, n, 2)] # 2 covers all even numbers for i in range(3, n, 2): non_primes.extend([j for j in range(i*2, n, i)]) return set([i for i in range(2, n)]) - set(non_primes) def getCircularPrimes(n): primes = getPrimes(n) is_circ = [] for prime in primes: prime_str = str(prime) iter_count = len(prime_str) - 1 rotated_num = [] while iter_count > 0: prime_str = prime_str[1:] + prime_str[:1] rotated_num.append(int(prime_str)) iter_count -= 1 if primes >= set(rotated_num): is_circ.append(prime) return len(is_circ)

    Read the article

  • Failed to get i915 symbols, graphics turbo disabled

    - by Optimus Prime
    I'm getting "Failed to get i915 symbols, graphics turbo disabled" error message after installing following softwares and few updates from Ubuntu. Django, Mysql server 5.5 Mysql benchmark And i have installed few updates for ubuntu. It was showing as Security Updates for Ubuntu. After installing Updates the update manager showed that i should restart the system. On restart i got following error message. " failed to get i915 symbols, graphics turbo disabled". So i tried the work around mentioned here (using the Live CD) ie add intel_ips to the blacklist echo "blacklist intel_ips" /etc/modprobe.d/blacklist.conf add i915 and intel_ips to /etc/modules echo -e "i915/nintel_ips" /etc/modules Now when start the system it freezes at Ubuntu splash screen. I'm using Ubuntu 12.04 LTS, on Dell inspiron N1040. I need to boot the system as i have spend lot of days configuring. Python and Django. Please help EDIT : OK when i restarted the system yesterday it magically turned on. Now i can view my desktop. But one problem, i can't mount any of the drives. It says failed to mount Drive. I'm also frequently getting "Ubuntu System Failure" Error Message.

    Read the article

  • Automated testing tool development challenges (for embedded software)

    - by Karthi prime
    My boss want to come up with the proposal for the following tool: An IDE: Able to build, compile, debug, via JTAG programming for the micro-controller. A Test Suite, reads the code in the IDE, auto generates the test cases, and it gives the in-target unit testing results(which is done by controlling code execution in the micro-controller via IDE). A no-overhead code coverage tool which interacts with the test suite and IDE. My work is to obtain the high level architecture of this tool, so as to proceed further. My current knowledge: There are tool-chains available from the chip manufacturer for the micro-controllers which can be utilized along with an open-source IDE like Eclipse, and along with an open-source burner, a complete IDE for a micro-controller can be done. Test cases can be auto-generated by reading the source file through the process of parsing, scripting, based on keywords. Test suite must be able to command the IDE to control, through breakpoints, and read the register contents from the microcontroller - This enables the in-target unit testing. An no-overhead code coverage should be done by no-overhead code instrumentation so as to execute those in the resource constraint environment of the micro-controller. I have the following questions: Any advice on the validity of my understanding? What are the challenges I will have during the development? What are the helpful open-source tools regarding this? What is the development time for this software? Thanks

    Read the article

  • Python - Check if numbers in list are factors of a number

    - by Zach
    Hey, I have a list of numbers (integers) (say, from 1 to 10). They're not necessarily consecutive, but they are in ascending order. I've prompted the user multiple times to enter a choice of the available numbers. When that number is entered, it is removed from the list along with any of its factors that may be there. I've prevented the user from selecting prime numbers. However, at some point in time, there may be non-prime numbers there, which have no factors remaining. I'm relatively new to Python, so I'm having trouble implementing: Checking if the number selected has no factors remaining (even if it is not prime). Checking if only prime numbers remain, or numbers without factors. I'm thinking of using for statements, but I'm not sure exactly how to implement them. Can anyone offer advice, or code? Thanks in advance... PS. In case anyone's wondering, I'm doing an implementation of the game of Taxman in Python.

    Read the article

  • Speed up bitstring/bit operations in Python?

    - by Xavier Ho
    I wrote a prime number generator using Sieve of Eratosthenes and Python 3.1. The code runs correctly and gracefully at 0.32 seconds on ideone.com to generate prime numbers up to 1,000,000. # from bitstring import BitString def prime_numbers(limit=1000000): '''Prime number generator. Yields the series 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ... using Sieve of Eratosthenes. ''' yield 2 sub_limit = int(limit**0.5) flags = [False, False] + [True] * (limit - 2) # flags = BitString(limit) # Step through all the odd numbers for i in range(3, limit, 2): if flags[i] is False: # if flags[i] is True: continue yield i # Exclude further multiples of the current prime number if i <= sub_limit: for j in range(i*3, limit, i<<1): flags[j] = False # flags[j] = True The problem is, I run out of memory when I try to generate numbers up to 1,000,000,000. flags = [False, False] + [True] * (limit - 2) MemoryError As you can imagine, allocating 1 billion boolean values (1 byte 4 or 8 bytes (see comment) each in Python) is really not feasible, so I looked into bitstring. I figured, using 1 bit for each flag would be much more memory-efficient. However, the program's performance dropped drastically - 24 seconds runtime, for prime number up to 1,000,000. This is probably due to the internal implementation of bitstring. You can comment/uncomment the three lines to see what I changed to use BitString, as the code snippet above. My question is, is there a way to speed up my program, with or without bitstring?

    Read the article

  • Error: "an object reference is required for the non-static field, method or property..."

    - by user300484
    Hi! Im creating an application on C#. Its function is to evualuate if a given is prime and if the same swapped number is prime as well. When I build my solution on Visual Studio, it says that "an object reference is required for the non-static field, method or property...". Im having this problem with the "volteado" and "siprimo" methods. Can you tell me where is the problem and how i can fix it? thank you! namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.Write("Write a number: "); long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user long av = volteado(a); // av is "a" but swapped if (siprimo(a) == false && siprimo(av) == false) Console.WriteLine("Both original and swapped numbers are prime."); else Console.WriteLine("One of the numbers isnt prime."); Console.ReadLine(); } private bool siprimo(long a) {// evaluate if the received number is prime bool sp = true; for (long k = 2; k <= a / 2; k++) if (a % k == 0) sp = false; return sp; } private long volteado(long a) {// swap the received number long v = 0; while (a > 0) { v = 10 * v + a % 10; a /= 10; } return v; } } }

    Read the article

  • Have I checked every consecutive subset of this list?

    - by Nathan
    I'm trying to solve problem 50 on Project Euler. Don't give me the answer or solve it for me, just try to answer this specific question. The goal is to find the longest sum of consecutive primes that adds to a prime below one million. I use wrote a sieve to find all the primes below n, and I have confirmed that it is correct. Next, I am going to check the sum of each subset of consecutive primes using the following method: I have a empty list sums. For each prime number, I add it to each element in sums and check the new sum, then I append the prime to sums. Here it is in python primes = allPrimesBelow(1000000) sums = [] for p in primes: for i in range(len(sums)): sums[i] += p check(sums[i]) sums.append(p) I want to know if I have called check() for every sum of two or more consecutive primes below one million The problem says that there is a prime, 953, that can be written as the sum of 21 consecutive primes, but I am not finding it.

    Read the article

  • numerical computation locks up ruby

    - by kolosy
    i'm trying to implement an id obfuscation scheme, with a simple hash borrowed elsewhere. i've added a method on the application helper: @@M_ID = 2**31-1 @@PRIME = 1580030173 @@PRIME_INVERSE = 59260789 # (calculated from MAXID and PRIME offline) def obfuscate_id(x) if x return ((x * @@PRIME) & @@M_ID) else x end end for some reason, whenever this is called, ruby locks up, and starts eating up disk space on my mac... like - gigs of it. any ideas?

    Read the article

  • Sorting in Lua, counting number of items

    - by Josh
    Two quick questions (I hope...) with the following code. The script below checks if a number is prime, and if not, returns all the factors for that number, otherwise it just returns that the number prime. Pay no attention to the zs. stuff in the script, for that is client specific and has no bearing on script functionality. The script itself works almost wonderfully, except for two minor details - the first being the factor list doesn't return itself sorted... that is, for 24, it'd return 1, 2, 12, 3, 8, 4, 6, and 24 instead of 1, 2, 3, 4, 6, 8, 12, and 24. I can't print it as a table, so it does need to be returned as a list. If it has to be sorted as a table first THEN turned into a list, I can deal with that. All that matters is the end result being the list. The other detail is that I need to check if there are only two numbers in the list or more. If there are only two numbers, it's a prime (1 and the number). The current way I have it does not work. Is there a way to accomplish this? I appreciate all the help! function get_all_factors(number) local factors = 1 for possible_factor=2, math.sqrt(number), 1 do local remainder = number%possible_factor if remainder == 0 then local factor, factor_pair = possible_factor, number/possible_factor factors = factors .. ", " .. factor if factor ~= factor_pair then factors = factors .. ", " .. factor_pair end end end factors = factors .. ", and " .. number return factors end local allfactors = get_all_factors(zs.param(1)) if zs.func.numitems(allfactors)==2 then return zs.param(1) .. " is prime." else return zs.param(1) .. " is not prime, and its factors are: " .. allfactors end

    Read the article

  • Where is the error in my code?

    - by Lulu Larson
    /** Yields: a String that contains each capital Letter (in 'A'..'Z') whose representation is prime */ public static String primeChars() { String s = ""; // inv: s contains each capital in "A'..c-1 whose representation is prime for (char c = 'A'; c <= 'Z'; c=(char)(c+1)) { if (Loops.isPrime((int)c) == true) { s= s+1; } } // s contains each capital in 'A' ..'Z' whose rep is a prime return s; }

    Read the article

  • dividing two array elements

    - by pradeep
    main() { int prime_array[2339],prime1_count=0,mul1_count=0; int i, prime, lim_up, lim_low, n,j=0; int mul,count=0; int mul_count[65026]={0},number[7096]; printf("\n ENTER THE LOWER LIMIT…: "); scanf("%d", &lim_low); printf("\n ENTER THE UPPER LIMIT…: "); scanf("%d", &lim_up); for(n=lim_low+1; n<lim_up; n++) { prime = 1; for(i=2; i<n; i++) if(n%i == 0) { prime = 0; break; } if(prime) { prime_array[j]=n; j++; } } for(i=1;i<=255;i++) { for(j=1;j<=255;j++) { mul = j*i; mul_count[mul]++; } } for(i=1;i<=65025;i++) if( mul_count[i]!=2 && mul_count[i]!=0 ) { number[count]=i; count++; } for(prime1_count=0;prime1_count<2339;prime1_count++) { printf("\nprime number used is:%d",prime_array[prime1_count]); for(mul1_count=0;mul1_count<7096;mul1_count++) { printf("\n%d\t",number[mul1_count] % prime_array[prime1_count]); } } } I want to find the modulus of (number[mul1_count] % prime_array[prime1_count] ), but the output which I get is wrong. What is the mistake here. The prime number should be in the range 40000 to 65025. What changes should i make here?

    Read the article

  • Else without if

    - by user2808951
    I'm trying to write a code for my computer programming class for a project due Monday, and I'm pretty new to Java, but I'm trying to write a program that will first determine if a number the user inputs is even or odd and then determine if the number is prime or not. I'm not sure if I did the algorithm right or not, so if anyone has any corrections on the program to my algorithm or anything else please say so, but my real issue is that the program is refusing to compile. Every time I try, it says it's having an else without if problem. Here's a link to my command box: http://s1341.photobucket.com/user/Emi_Nightshade/media/Capture_zps45f9a2ea.png.html Here's my code: import java.io.*; import java.util.*; public class Lesson9p1_ThuotteEmily { public static void main(String args[]) { Scanner kbReader0=new Scanner(System.in); System.out.print("\n\nPlease enter an integer. An integer is whole number, and it can be either negative or positive. Please enter your number: "); long num=kbReader0.nextLong(); if(num%2==0) //if and else with braces { System.out.println("Your integer " + num + " is even."); } else { System.out.println("Your integer " + num + " is odd."); } Scanner kbReader1=new Scanner(System.in); System.out.print("\n\nWould you like to know if your number is prime? Please enter yes or no: "); String yn=kbReader1.nextLine(); if(yn.equals.IgnoreCase("Yes")) { System.out.println("Okay. Give me a moment."); { if(num%2==0) { System.out.println("Your number isn't prime."); } else if(num==2) { System.out.println("Your number is 2, which is the only even prime number in existence. Cool, right?"); } for(int i=3;i*i<=n;i+=2) { if(n%1==0) { System.out.println("Your number isn't prime."); } } else { System.out.println("Your number is prime!"); } } } if(yn.equals.IgnoreCase("No")) { System.out.println("Okay."); } } } If anyone could help me out with this and also any problems I may have made elsewhere in the program, I'd be very grateful! Thanks.

    Read the article

  • How well does ubuntu run on the asus Eee tablet? please read details before answering

    - by Const
    Im considering buying an Asus Eee transformer prime, i mainly want it so I can do some light web coding on the go, I commute a lot, most of my time is spent on the trains unfortunately. I know that it is possible to install ubuntu on the transformer prime, im also aware that it is not stable since its something new. Im wondering if anyone has tried it, how responsive/ fast is it? Does the batter die quickly?

    Read the article

  • Call methods in main method

    - by Niloo
    this is my main method that gets 3 integers from command line and I parse then in my validating method. However I have one operation method that calls 3 other methods, but i don't know what type of data and howmany I have to put in my operatinMethod() " cuase switch only gets one); AND also in my mainMethod() for calling the operationMehod(); itself? please let me know if i'm not clear? Thanx! main method: public class test { // Global Constants final static int MIN_NUMBER = 1; final static int MAX_PRIME = 10000; final static int MAX_FACTORIAL = 12; final static int MAX_LEAPYEAR = 4000; //Global Variables static int a,b,c; public static void main (String[] args) { for(int i =0; i< args.length; i++){} if(validateInput(args[0],args[1],args[2])){ performOperations(); } } //Validate User Input public static boolean validateInput(String num1,String num2,String num3){ boolean isValid = false; try{ try{ try{ a = Integer.parseInt(num1); if(!withinRange(a,MIN_NUMBER, MAX_PRIME)) { System.out.println("The entered value " + num1 +" is out of range [1 TO 10000]."); } isValid = true; } catch(Exception ex) { System.out.println("The entered value " + num1 + " is not a valid integer. Please try again."); } b = Integer.parseInt(num2); if(!withinRange(b,MIN_NUMBER, MAX_FACTORIAL)) { System.out.println("The entered value " + num2 +" is out of range [1 TO 12]."); } isValid = true; } catch(Exception ex) { System.out.println("The entered value " + num2 + " is not a valid integer. Please try again."); } c = Integer.parseInt(num3); if(!withinRange(c,MIN_NUMBER, MAX_LEAPYEAR)) { System.out.println("The entered value " + num3 +" is out of range [1 TO 4000]."); } isValid = true; } catch(Exception ex) { System.out.println("The entered value " + num3 + " is not a valid integer. Please try again."); } return isValid; } //Check the value within the specified range private static boolean withinRange(int userInput ,int min, int max){ boolean isInRange = true; if(userInput < min || userInput > max){ isInRange = false; } return isInRange; } //Perform operations private static void performOperations(int userInput) { switch(userInput) { case 1: // count Prime numbers countPrimes(a); break; case 2: // Calculate factorial getFactorial(b); break; case 3: // find Leap year isLeapYear(c); break; } } // Verify Prime Number private static boolean isPrime(int prime) { for(int i = 2; i <= Math.sqrt(prime) ; i++) { if ((prime % i) == 0) { return false; } } return true; } // Calculate Prime private static int countPrimes(int userInput){ int count =0; for(int i=userInput; i<=MAX_PRIME; i++) { if(isPrime(i)){ count++; } } System.out.println("Exactly "+ count + " prime numbers exist between "+ a + " and 10,000."); return count; } // Calculate the factorial value private static int getFactorial(int userInput){ int ans = userInput; if(userInput >1 ){ ans*= (getFactorial(userInput-1)); //System.out.println("The value of "+ b +"! is "+ getFactorial(userInput)); } return ans; } // Determine whether the integer represents a leap year private static boolean isLeapYear(int userInput){ if (userInput % 4 == 0 && userInput % 400 == 0 && userInput % 100 ==0){ System.out.println("The year "+ c +" is a leap year"); } else { System.out.println("The year "+ c +" is a not leap year"); } return false; } }

    Read the article

  • Algorithmic problem - quickly finding all #'s where value %x is some given value

    - by Steve B.
    Problem I'm trying to solve, apologies in advance for the length: Given a large number of stored records, each with a unique (String) field S. I'd like to be able to find through an indexed query all records where Hash(S) % N == K for any arbitrary N, K (e.g. given a million strings, find all strings where HashCode(s) % 17 = 5. Is there some way of memoizing this so that we can quickly answer any question of this form without doing the % on every value? The motivation for this is a system of N distributed nodes, where each record has to be assigned to at least one node. The nodes are numbered 0 - (K-1) , and each node has to load up all of the records that match it's number: If we have 3 nodes Node 0 loads all records where Hash % 3 ==0 Node 1 loads all records where Hash % 3 ==1 Node 2 loads all records where Hash % 3 ==2 adding a 4th node, obviously all the assignments have to be recomputed - Node 0 loads all records where Hash % 4 ==0 ... etc I'd like to easily find these records through an indexed query without having to compute the mod individually. The best I've been able to come up with so far: If we take the prime factors of N (p1 * p2 * ... ) if N % M == I then p % M == I % p for all of N's prime factors e.g. 10 nodes : N % 10 == 6 then N % 2 = 0 == 6 %2 N % 5 = 1 == 6 %5 so storing an array of the "%" of N for the first "reasonable" number of primes for my data set should be helpful. For example in the above example we store the hash and the primes HASH PRIMES (array of %2, %3, %5, %7, ... ]) 16 [0 1 1 2 .. ] so looking for N%10 == 6 is equivalent to looking for all values where array[1]==1 and array[2] == 1. However, this breaks at the first prime larger than the highest number I'm storing in the factor table. Is there a better way?

    Read the article

  • Most efficient way to store this collection of moduli and remainders?

    - by Bryan
    I have a huge collection of different moduli and associated with each modulus a fairly large list of remainders. I want to store these values so that I can efficiently determine whether an integer is equivalent to any one of the remainders with respect to any of the moduli (it doesn't matter which, I just want a true/false return). I thought about storing these values as a linked-list of balanced binary trees, but I was wondering if there is a better way? EDIT Perhaps a little more detail would be helpful. As for the size of this structure, it will be holding about 10s of thousands of (prime-1) moduli and associated to each modulus will be a variable amount of remainders. Most moduli will only have one or two remainders associated to it, but a very rare few will have a couple hundred associated to it. This is part of a larger program which handles numbers with a couple thousand (decimal) digits. This program will benefit more from this table being as large as possible and being able to be searched quickly. Here's a small part of the dataset where the moduli are in parentheses and the remainders are comma separated: (46) k = 20 (58) k = 15, 44 (70) k = 57 (102) k = 36, 87 (106) k = 66 (156) k = 20, 59, 98, 137 (190) k = 11, 30, 68, 87, 125, 144, 182 (430) k = 234 (520) k = 152, 282 (576) k = 2, 11, 20, 29, 38, 47, 56, 65, 74, ...(add 9 each time), 569 I had said that the moduli were prime, but I was wrong they are each one below a prime.

    Read the article

  • Integer type or not [closed]

    - by kira
    I am writing a program (in cpp) to check the primality of a given number The point where i am struck is , I need to check in between the program wether the value i obtained upon some arithmetic operations on the input is an integer or not i.e lets say input is 'a' I want to know how to check if 'b' is integer or not (FYI, b=(a+1)/6 ) My attempt for this : int main() { using std::cin; using std::cout; int b,c; int a; cout<<"enter the number"; cin>>a; b=(a+1)/6; c=(a-1)/6; if (b is an integer) cout << "The given number is prime"; else if (c is an integer) cin << "The given number is prime!"; else cout<<"The number is not prime"; return 0; }

    Read the article

  • Connect to a webserver running in Windows 7 using IP from a brower

    - by Optimus Prime
    I'm not sure if this is the proper place to ask this question. Here is my issue I'm using windows 7 and i have installed Zope Server.(Zope is python web framework which has a built-in server). I can connect to this server from my browser by typing, localhost:8080 But if i try to connect this server from another machine using my IP or even from my own system it doesn't work. ie xxx.xxx.xx.xxx:8080

    Read the article

  • Help making this code run faster for spoj.

    - by Josh Meredith
    I've been doing a few of the challenges on the Sphere Online Judge, but I can't seem to get the second problem (the prime generator) to run within the time limit. Does anyone have any tips for increasing the speed of the following code? #include <stdio.h> #include <math.h> int is_prime(int n); void make_sieve(); void fast_prime(int n); int primes[16000]; int main() { int nlines; int m, n; make_sieve(); scanf("%d", &nlines); for (; nlines >= 1; nlines--) { scanf("%d %d", &m, &n); if (!(m % 2)) { m++; } for ( ; m < n; m+=2) { fast_prime(m); } printf("\n"); } return 0; } /* Prints a number if it's prime. */ inline void fast_prime(int n) { int j; for (int i = 0; ((j = primes[i]) > -1); i++) { if (!(n % j)) { return; } } printf("%d\n", n); } /* Create an array listing prime numbers. */ void make_sieve() { int j = 0; for (int i = 0; i < 16000; i++) { primes[i] = -1; } for (int i = 2; i < 32000; i++) { if (i % 2) { if (is_prime(i)) { primes[j] = i; j++; } } } return; } /* Test if a number is prime. Return 1 if prime. Return 0 if not. */ int is_prime(int n) { int rootofn; rootofn = sqrt(n); if ((n <= 2) || (n == 3) || (n == 5) || (n == 7)) { return 1; } if (((n % 2) == 0) || ((n % 3) == 0) || ((n % 5) == 0) || ((n % 7) == 0)) { return 0; } for (int i = 11; i < rootofn; i += 2) { if ((n % i) == 0) { return 0; } } return 1; }

    Read the article

  • Recursively adding threads to a Java thread pool

    - by Leith
    I am working on a tutorial for my Java concurrency course. The objective is to use thread pools to compute prime numbers in parallel. The design is based on the Sieve of Eratosthenes. It has an array of n bools, where n is the largest integer you are checking, and each element in the array represents one integer. True is prime, false is non prime, and the array is initially all true. A thread pool is used with a fixed number of threads (we are supposed to experiment with the number of threads in the pool and observe the performance). A thread is given a integer multiple to process. The thread then finds the first true element in the array that is not a multiple of thread's integer. The thread then creates a new thread on the thread pool which is given the found number. After a new thread is formed, the existing thread then continues to set all multiples of it's integer in the array to false. The main program thread starts the first thread with the integer '2', and then waits for all spawned threads to finish. It then spits out the prime numbers and the time taken to compute. The issue I have is that the more threads there are in the thread pool, the slower it takes with 1 thread being the fastest. It should be getting faster not slower! All the stuff on the internet about Java thread pools create n worker threads the main thread then wait for all threads to finish. The method I use is recursive as a worker can spawn more worker threads. I would like to know what is going wrong, and if Java thread pools can be used recursively.

    Read the article

  • Why does my ActivePerl program report 'Sorry. Ran out of threads'?

    - by Zaid
    Tom Christiansen's example code (à la perlthrtut) is a recursive, threaded implementation of finding and printing all prime numbers between 3 and 1000. Below is a mildly adapted version of the script #!/usr/bin/perl # adapted from prime-pthread, courtesy of Tom Christiansen use strict; use warnings; use threads; use Thread::Queue; sub check_prime { my ($upstream,$cur_prime) = @_; my $child; my $downstream = Thread::Queue->new; while (my $num = $upstream->dequeue) { next unless ($num % $cur_prime); if ($child) { $downstream->enqueue($num); } else { $child = threads->create(\&check_prime, $downstream, $num); if ($child) { print "This is thread ",$child->tid,". Found prime: $num\n"; } else { warn "Sorry. Ran out of threads.\n"; last; } } } if ($child) { $downstream->enqueue(undef); $child->join; } } my $stream = Thread::Queue->new(3..shift,undef); check_prime($stream,2); When run on my machine (under ActiveState & Win32), the code was capable of spawning only 118 threads (last prime number found: 653) before terminating with a 'Sorry. Ran out of threads' warning. In trying to figure out why I was limited to the number of threads I could create, I replaced the use threads; line with use threads (stack_size => 1);. The resultant code happily dealt with churning out 2000+ threads. Can anyone explain this behavior?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >