Search Results

Search found 557 results on 23 pages for 'optimus prime'.

Page 7/23 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Determine if a number is a prime with regex?

    - by kitlite
    I found the following code example for Java on RosettaCode: public static boolean prime(int n) { return !new String(new char[n]).matches(".?|(..+?)\\1+"); } I don't know Java in particular but understand all aspects of this snippet except for the regex itself I have basic to basic-advanced knowledge of Regex as you find it in the built-in PHP functions How does .?|(..+?)\\1+ match prime numbers?

    Read the article

  • Can I set my Optimus Nvidia card to run Unity3D with bumblebee?

    - by manuhalo
    I'd like to know whether I can run compiz on my Nvidia card to speed things up. It's a Dell XPS15 laptop but I'm mostly using it as a desktop, so battery life is not important. Apparently my Intel integrated card is able to run unity 3D, but my Nvidia GT 420M is not. Here's the output of unity_support_test, both with optirun and without it: manuhalo@Ubuntu-XPS-L501X:~$ optirun /usr/lib/nux/unity_support_test -p OpenGL vendor string: NVIDIA Corporation OpenGL renderer string: GeForce GT 420M/PCI/SSE2 OpenGL version string: 4.1.0 NVIDIA 280.13 Not software rendered: yes Not blacklisted: yes GLX fbconfig: yes GLX texture from pixmap: no GL npot or rect textures: yes GL vertex program: yes GL fragment program: yes GL vertex buffer object: yes GL framebuffer object: yes GL version is 1.4+: yes Unity 3D supported: no manuhalo@Ubuntu-XPS-L501X:~$ /usr/lib/nux/unity_support_test -p OpenGL vendor string: Tungsten Graphics, Inc OpenGL renderer string: Mesa DRI Intel(R) Ironlake Mobile OpenGL version string: 2.1 Mesa 7.11 Not software rendered: yes Not blacklisted: yes GLX fbconfig: yes GLX texture from pixmap: yes GL npot or rect textures: yes GL vertex program: yes GL fragment program: yes GL vertex buffer object: yes GL framebuffer object: yes GL version is 1.4+: yes Unity 3D supported: yes Any ideas of why this is happening? Thanks in advance to anyone able to shed some light on this. What I have tried: Installed the v290 drivers from the x-stable PPA. Tried forcing Unity-3D to work by telling Unity to ignore the unity-support-test results i.e. gksudo gedit /etc/environment add the following UNITY_FORCE_START=1 to the end of the file.

    Read the article

  • Why is my "Page [0]" not centered in my webpage?

    - by William
    My "Page [0]" text isn't centered on my webpage. Anyone know why? I could really use some help please. Here is the html: <html> <head> <title>Test Forum</title> <link href="http://prime.programming-designs.com/test_forum/style.css" rel="stylesheet" type="text/css" /> </head> <body> <a href="http://prime.programming-designs.com/test_forum/"><img src="http://prime.programming-designs.com/test_forum//images/banner1.png" alt="" id="banner" /></a> <h1>Test Forums</h1> <hr /> <div id="navi"><div id="naviheader">Boards</div><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=0">Testing</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=1">General Discussion</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=2">Video Games</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=3">Anime and Manga</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=4">BlazBlue</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=5">Shin Megami Tensei</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=6">Earthbound</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=7">Phantasy Star</a><br /><a href="http://prime.programming-designs.com/test_forum/viewboard.php?board=8">Mobile Suit Gundam</a><br /></div> <div class="postbox"><h4>CyanPrime</h4><hr />Welcome to the King's Gate BBS!</div>Page: [<a href="http://prime.programming-designs.com/test_forum/index.php?page=0">0</a>] </body> </html> Here is the CSS: @charset "windows-1252"; body{ background-color: #EEFFF8; color: #000000; text-align: center; } .postbox{ text-align: left; margin: auto; background-color: #dbfef8; border: 1px solid #82FFCD; width: 50%; margin-top: 10px; } .stickypostbox{ text-align: left; margin: auto; background-color: #F5FFFA; border: 1px solid #82FFCD; width: 50%; margin-top: 10px; } h4{ margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; color: #9932CC; } h1{ color: #551A8B; } hr{ color: #82FFCD; background-color: #82FFCD; height: 1px; border: 0px dotted #82FFCD; } a{ color: #7F00FF; text-decoration: none; } a:hover{ color: #7F00FF; text-decoration: underline; } form{ margin: 0px auto; width: 50%; } #formdiv { background-color:#dbfef8; border:1px solid #82FFCD; } .fielddiv1{ background-color: #f9f9f9; border: 1px solid #DBFEF8; vertical-align: middle; width: 45%; float: left; } .fielddiv2{ background-color: #f9f9f9; border: 1px solid #DBFEF8; vertical-align: middle; width: 100%; } .fieldtext1{ width: 50%; background-color: #82FFCD; float: left; } .fieldtext2{ width: 100%; background-color: #82FFCD; } #replydiv{ width: 100%; background-color: #DBFEF8; margin: 10px 0 10px 0; } #admindiv{ width: 100%; background-color: #DBFEF8; margin: 10px 0 10px 0; } #navi{ width: 200px; background-color: #dbfef8; border: 1px solid #82FFCD; text-align: left; float: left; } #naviheader{ width: 100%; background-color: #82FFCD; } #submitbutton{ border: 1px solid #82FFCD; background-color: #DBFEF8; color: #000000; margin-top: 5px; width: 100px; height: 20px; } #banner{ border: 1px solid #82FFCD; } .postbar{ margin-right: 0px; margin-top: 0px; } .bannedtext{ margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; color: #FF0000; } And here is the webpage so you can get some context (you'll notice that my "page [0]" is centered on the other boards, but not the index. http://prime.programming-designs.com/test_forum/

    Read the article

  • Tab Sweep - Java EE wins, Prime Faces JSF, NetBeans, Jelastic for GlassFish, BeanValidation, Ewok and more...

    - by alexismp
    Recent Tips and News on Java, Java EE 6, GlassFish & more : • PrimeFaces 3.2 Final Released (primefaces.org) • Java EE wins over Spring (Bill Burke) • Customizing Components in JSF 2.0 (Mr. Bool) • Key to the Java EE 6 Platform: NetBeans IDE 7.1.x (OTN) • How to use GlassFish’s Connection Pool in Jelastic (jelastic.com) • Bean Validation 1.1 early draft 1 is out - time for feedback (Emmanuel) • Code artifacts published for Bean Validation 1.1 early draft 1 (Emmanuel) • Aprendendo Java EE 6 com GlassFish 3 e NetBeans 7.1 (Marcello) • JavaEE6 and the Ewoks (Murat)

    Read the article

  • Project Euler: Programmatic Optimization for Problem 7?

    - by bmucklow
    So I would call myself a fairly novice programmer as I focused mostly on hardware in my schooling and not a lot of Computer Science courses. So I solved Problem 7 of Project Euler: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? I managed to solve this without problem in Java, but when I ran my solution it took 8 and change seconds to run. I was wondering how this could be optimized from a programming standpoint, not a mathematical standpoint. Is the array looping and while statements the main things eating up processing time? And how could this be optimized? Again not looking for a fancy mathematical equation..there are plenty of those in the solution thread. SPOILER My solution is listed below. public class PrimeNumberList { private ArrayList<BigInteger> primesList = new ArrayList<BigInteger>(); public void fillList(int numberOfPrimes) { primesList.add(new BigInteger("2")); primesList.add(new BigInteger("3")); while (primesList.size() < numberOfPrimes){ getNextPrime(); } } private void getNextPrime() { BigInteger lastPrime = primesList.get(primesList.size()-1); BigInteger currentTestNumber = lastPrime; BigInteger modulusResult; boolean prime = false; while(!prime){ prime = true; currentTestNumber = currentTestNumber.add(new BigInteger("2")); for (BigInteger bi : primesList){ modulusResult = currentTestNumber.mod(bi); if (modulusResult.equals(BigInteger.ZERO)){ prime = false; break; } } if(prime){ primesList.add(currentTestNumber); } } } public BigInteger get(int primeTerm) { return primesList.get(primeTerm - 1); } }

    Read the article

  • Effective java hashcode implementation

    - by Scobal
    I was wondering if someone could explain in detail what (int)(l ^ (l >>> 32)); does in the following hashcode implementation (generated by eclipse, but the same as Effective Java): private int i; private char c; private boolean b; private short s; private long l; private double d; private float f; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + i; result = prime * result + s; result = prime * result + (b ? 1231 : 1237); result = prime * result + c; long t = Double.doubleToLongBits(d); result = prime * result + (int) (t ^ (t >>> 32)); result = prime * result + Float.floatToIntBits(f); result = prime * result + (int) (l ^ (l >>> 32)); return result; } Thanks!

    Read the article

  • Project Euler #3

    - by Alex
    Question: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? I found this one pretty easy, but running the file took an extremely long time, it's been going on for a while and the highest number I've got to is 716151937. Here is my code, am I just going to have a wait or is there an error in my code? //User made class public class Three { public static boolean checkPrime(long p) { long i; boolean prime = false; for(i = 2;i<p/2;i++) { if(p%i==0) { prime = true; break; } } return prime; } } //Note: This is a separate file public class ThreeMain { public static void main(String[] args) { long comp = 600851475143L; boolean prime; long i; for(i=2;i<comp/2;i++) { if(comp%i==0) { prime = Three.checkPrime(i); if(prime==true) { System.out.println(i); } } } } }

    Read the article

  • Why should the "prime-based" hashcode implmentation be used instead of the "naive" one?

    - by Wilhelm
    I have seen that a prime number implmentation of the GetHashCode function is being recommend, for example here. However using the following code (in VB, sorry), it seems as if that implementation gives the same hash density as a "naive" xor implementation. If the density is the same, I would suppose there is the same probability of cllision in both implementations. Am I missing anything on why is the prime approach preferred? I am supossing that if the hash code is a byte I do not lose generality for the integer case. Sub Main() Dim XorHashes(255) As Integer Dim PrimeHashes(255) As Integer For i = 0 To 255 For j = 0 To 255 For k = 0 To 255 XorHashes(GetXorHash(i, j, k)) += 1 PrimeHashes(GetPrimeHash(i, j, k)) += 1 Next Next Next For i = 0 To 255 Console.WriteLine("{0}: {1}, {2}", i, XorHashes(i), PrimeHashes(i)) Next Console.ReadKey() End Sub Public Function GetXorHash(ByVal valueOne As Integer, ByVal valueTwo As Integer, ByVal valueThree As Integer) As Byte Return CByte((valueOne Xor valueTwo Xor valueThree) Mod 256) End Function Public Function GetPrimeHash(ByVal valueOne As Integer, ByVal valueTwo As Integer, ByVal valueThree As Integer) As Byte Dim TempHash = 17 TempHash = 31 * TempHash + valueOne TempHash = 31 * TempHash + valueTwo TempHash = 31 * TempHash + valueThree Return CByte(TempHash Mod 256) End Function

    Read the article

  • Interview question : What is the fastest way to generate prime number recursively ?

    - by hilal
    Generation of prime number is simple but what is the fastest way to find it and generate( prime numbers) it recursively ? Here is my solution. However, it is not the best way. I think it is O(N*sqrt(N)). Please correct me, if I am wrong. public static boolean isPrime(int n) { if (n < 2) { return false; } else if (n % 2 == 0 & n != 2) { return false; } else { return isPrime(n, (int) Math.sqrt(n)); } } private static boolean isPrime(int n, int i) { if (i < 2) { return true; } else if (n % i == 0) { return false; } else { return isPrime(n, --i); } } public static void generatePrimes(int n){ if(n < 2) { return ; } else if(isPrime(n)) { System.out.println(n); } generatePrimes(--n); } public static void main(String[] args) { generatePrimes(200); }

    Read the article

  • Removing words from a file

    - by user1765792
    I'm trying to take a regular text file and remove words identified in a separate file (stopwords) containing the words to be removed separated by carriage returns ("\n"). Right now I'm converting both files into lists so that the elements of each list can be compared. I got this function to work, but it doesn't remove all of the words I have specified in the stopwords file. Any help is greatly appreciated. def elimstops(file_str): #takes as input a string for the stopwords file location stop_f = open(file_str, 'r') stopw = stop_f.read() stopw = stopw.split('\n') text_file = open('sample.txt') #Opens the file whose stop words will be eliminated prime = text_file.read() prime = prime.split(' ') #Splits the string into a list separated by a space tot_str = "" #total string i = 0 while i < (len(stopw)): if stopw[i] in prime: prime.remove(stopw[i]) #removes the stopword from the text else: pass i += 1 # Creates a new string from the compilation of list elements # with the stop words removed for v in prime: tot_str = tot_str + str(v) + " " return tot_str

    Read the article

  • [0-9a-zA-Z]* string expressed with primes or prime-factorization-style way to break it into parts?

    - by HH
    Suppose a string consists of numbers and alphabets. You want to break it into parts, an analogy is primes' factorization, but how can you do similar thing with strings [0-9a-zA-Z]* or even with arbitrary strings? I could express it in alphabets and such things with octal values and then prime-factorize it but then I need to keep track of places where I had the non-numbers things. Is there some simple way to do it? I am looking for simple succinct solutions and don't want too much side-effects. [Update] mvds has the correct idea, to change the base, how would you implement it?

    Read the article

  • Count the number of ways in which a number 'A' can be broken into a sum of 'B' numbers such that all numbers are co-prime to 'C'

    - by rajneesh2k10
    I came across the solution of a problem which involve dynamic-programming approach, solved using a three dimensional matrix. Link to actual problem is: http://community.topcoder.com/stat?c=problem_statement&pm=12189&rd=15177 Solution to this problem is here under MuddyRoad2: http://apps.topcoder.com/wiki/display/tc/SRM+555 In the last paragraph of explanation, author describes a dynamic programming approach to count the number of ways in which a number 'A' can be broken into a sum of 'B' numbers (not necessarily different), such that every number is co-prime to 3 and the order in which these numbers appear does matter. I am not able to grasp that approach. Can anyone help me understand how DP is acting here. I can't understand what is a state here and how it is derived from the previous state.

    Read the article

  • Project Euler 10: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 10.  As always, any feedback is welcome. # Euler 10 # http://projecteuler.net/index.php?section=problems&id=10 # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. import time start = time.time() def primes_to_max(max): primes, number = [2], 3 while number < max: isPrime = True for prime in primes: if number % prime == 0: isPrime = False break if (prime * prime > number): break if isPrime: primes.append(number) number += 2 return primes primes = primes_to_max(2000000) print sum(primes) print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Most Elegant Way to write isPrime in java

    - by Anantha Kumaran
    public class Prime { public static boolean isPrime1(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } public static boolean isPrime2(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } } public class PrimeTest { public PrimeTest() { } @Test public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Prime prime = new Prime(); TreeMap<Long, String> methodMap = new TreeMap<Long, String>(); for (Method method : Prime.class.getDeclaredMethods()) { long startTime = System.currentTimeMillis(); int primeCount = 0; for (int i = 0; i < 1000000; i++) { if ((Boolean) method.invoke(prime, i)) { primeCount++; } } long endTime = System.currentTimeMillis(); Assert.assertEquals(method.getName() + " failed ", 78498, primeCount); methodMap.put(endTime - startTime, method.getName()); } for (Entry<Long, String> entry : methodMap.entrySet()) { System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds "); } } } I am trying to find the fastest way to check whether the given number is prime or not. This is what is finally came up with. Is there any better way than the second implementation(isPrime2).

    Read the article

  • How can I generate the Rowland prime sequence idiomatically in J?

    - by Gregory Higley
    If you're not familiar with the Rowland prime sequence, you can find out about it here. I've created an ugly, procedural monadic verb in J to generate the first n terms in this sequence, as follows: rowland =: monad define result =. 0 $ 0 t =. 1 $ 7 while. (# result) < y do. a =. {: t n =. 1 + # t t =. t , a + n +. a d =. | -/ _2 {. t if. d > 1 do. result =. ~. result , d end. end. result ) This works perfectly, and it indeed generates the first n terms in the sequence. (By n terms, I mean the first n distinct primes.) Here is the output of rowland 20: 5 3 11 23 47 101 7 13 233 467 941 1889 3779 7559 15131 53 30323 60647 121403 242807 My question is, how can I write this in more idiomatic J? I don't have a clue, although I did write the following function to find the differences between each successive number in a list of numbers, which is one of the required steps. Here it is, although it too could probably be refactored by a more experienced J programmer than I: diffs =: monad : '}: (|@({.-2&{.) , $:@}.) ^: (1 < #) y'

    Read the article

  • Beginner Question ; About Prime Generation in "C" - What is wrong with my code ? -

    - by alorsoncode
    I'm a third year irregular CS student and ,i just realized that i have to start coding. I passed my coding classes with lower bound grades so that i haven't a good background in coding&programming. I'm trying to write a code that generates prime numbers between given upper and lower bounds. Not knowing C well, enforce me to write a rough code then go over it to solve. I can easily set up the logic for intended function but i probably create a wrong algorithm through several different ways. Here I share my last code, i intend to calculate that when a number gives remainder Zero , it should be it self and 1 , so that count==2; What is wrong with my implementation and with my solution generating style? I hope you will warm me up to programming world, i couldn't find enough motivation and courage to get deep into programming. Thanks in Advance :) Stdio and Math.h is Included int primegen(int down,int up) { int divisor,candidate,count=0,k; for(candidate=down;candidate<=up;candidate++) { for(divisor=1;divisor<=candidate;divisor++) { k=(candidate%divisor); } if (k==0) count++; if(count==2) { printf("%d\n", candidate); count=0; } else { continue; } } } int main() { primegen(3,15); return 0; }

    Read the article

  • file output in python giving me garbage

    - by Richard
    When I write the following code I get garbage for an output. It is just a simple program to find prime numbers. It works when the first for loops range only goes up to 1000 but once the range becomes large the program fail's to output meaningful data output = open("output.dat", 'w') for i in range(2, 10000): prime = 1 for j in range(2, i-1): if i%j == 0: prime = 0 j = i-1 if prime == 1: output.write(str(i) + " " ) output.close() print "writing finished"

    Read the article

  • ASM programming, how to use loop?

    - by chris
    Hello. Im first time here.I am a college student. I've created a simple program by using assembly language. And im wondering if i can use loop method to run it almost samething as what it does below the program i posted. and im also eager to find someome who i can talk through MSN messanger so i can ask you questions right away.(if possible) ok thank you .MODEL small .STACK 400h .data prompt db 10,13,'Please enter a 3 digit number, example 100:',10,13,'$' ;10,13 cause to go to next line first_digit db 0d second_digit db 0d third_digit db 0d Not_prime db 10,13,'This number is not prime!',10,13,'$' prime db 10,13,'This number is prime!',10,13,'$' question db 10,13,'Do you want to contine Y/N $' counter dw 0d number dw 0d half dw ? .code Start: mov ax, @data ;establish access to the data segment mov ds, ax mov number, 0d LetsRoll: mov dx, offset prompt ; print the string (please enter a 3 digit...) mov ah, 9h int 21h ;execute ;read FIRST DIGIT mov ah, 1d ;bios code for read a keystroke int 21h ;call bios, it is understood that the ascii code will be returned in al mov first_digit, al ;may as well save a copy sub al, 30h ;Convert code to an actual integer cbw ;CONVERT BYTE TO WORD. This takes whatever number is in al and ;extends it to ax, doubling its size from 8 bits to 16 bits ;The first digit now occupies all of ax as an integer mov cx, 100d ;This is so we can calculate 100*1st digit +10*2nd digit + 3rd digit mul cx ;start to accumulate the 3 digit number in the variable imul cx ;it is understood that the other operand is ax ;AND that the result will use both dx::ax ;but we understand that dx will contain only leading zeros add number, ax ;save ;variable <number> now contains 1st digit * 10 ;---------------------------------------------------------------------- ;read SECOND DIGIT, multiply by 10 and add in mov ah, 1d ;bios code for read a keystroke int 21h ;call bios, it is understood that the ascii code will be returned in al mov second_digit, al ;may as well save a copy sub al, 30h ;Convert code to an actual integer cbw ;CONVERT BYTE TO WORD. This takes whatever number is in al and ;extends it to ax, boubling its size from 8 bits to 16 bits ;The first digit now occupies all of ax as an integer mov cx, 10d ;continue to accumulate the 3 digit number in the variable mul cx ;it is understood that the other operand is ax, containing first digit ;AND that the result will use both dx::ax ;but we understand that dx will contain only leading zeros. Ignore them add number, ax ;save -- nearly finished ;variable <number> now contains 1st digit * 100 + second digit * 10 ;---------------------------------------------------------------------- ;read THIRD DIGIT, add it in (no multiplication this time) mov ah, 1d ;bios code for read a keystroke int 21h ;call bios, it is understood that the ascii code will be returned in al mov third_digit, al ;may as well save a copy sub al, 30h ;Convert code to an actual integer cbw ;CONVERT BYTE TO WORD. This takes whatever number is in al and ;extends it to ax, boubling its size from 8 bits to 16 bits ;The first digit now occupies all of ax as an integer add number, ax ;Both my variable number and ax are 16 bits, so equal size mov ax, number ;copy contents of number to ax mov cx, 2h div cx ;Divide by cx mov half, ax ;copy the contents of ax to half mov cx, 2h; mov ax, number; ;copy numbers to ax xor dx, dx ;flush dx jmp prime_check ;jump to prime check print_question: mov dx, offset question ;print string (do you want to continue Y/N?) mov ah, 9h int 21h ;execute mov ah, 1h int 21h ;execute cmp al, 4eh ;compare je Exit ;jump to exit cmp al, 6eh ;compare je Exit ;jump to exit cmp al, 59h ;compare je Start ;jump to start cmp al, 79h ;compare je Start ;jump to start prime_check: div cx; ;Divide by cx cmp dx, 0h ;reset the value of dx je print_not_prime ;jump to not prime xor dx, dx; ;flush dx mov ax, number ;copy the contents of number to ax cmp cx, half ;compare half with cx je print_prime ;jump to print prime section inc cx; ;increment cx by one jmp prime_check ;repeat the prime check print_prime: mov dx, offset prime ;print string (this number is prime!) mov ah, 9h int 21h ;execute jmp print_question ;jumps to question (do you want to continue Y/N?) this is for repeat print_not_prime: mov dx, offset Not_prime ;print string (this number is not prime!) mov ah, 9h int 21h ;execute jmp print_question ;jumps to question (do you want to continue Y/N?) this is for repeat Exit: mov ah, 4ch int 21h ;execute exit END Start

    Read the article

  • Strange output produced by program

    - by Boom_mooB
    I think that my code works. However, it outputs 01111E5, or 17B879DD, or something like that. Can someone please tell me why. I am aware that I set the limit of P instead of 10,001. My code is like that because I start with 3, skipping the prime number 2. #include <iostream> bool prime (int i) { bool result = true; int isitprime = i; for(int j = 2; j < isitprime; j++) ///prime number tester { if(isitprime%j == 0) result = false; } return result; } int main (void) { using namespace std; int PrimeNumbers = 1; int x = 0; for (int i = 3 ; PrimeNumbers <=10000; i++) { if(prime(i)) { int prime = i; PrimeNumbers +=1; } } cout<<prime<<endl; system ("pause"); return 0; }

    Read the article

  • What is the smallest amount of bits you can write twin-prime calculation?

    - by HH
    A succinct example in Python, its source. Explanation about the syntactic sugar here. s=p=1;exec"if s%p*s%~-~p:print`p`+','+`p+2`\ns*=p*p;p+=2\n"*999 The smallest amount of bits is defined by the smallest amount of 4pcs of things you can see with hexdump, it is not that precise measure but well-enough until an ambiguity. $ echo 's=p=1;exec"if s%p*s%~-~p:print`p`+','+`p+2`\ns*=p*p;p+=2\n"*999' > .test $ hexdump .test | wc 5 36 200 $ hexdump .test 0000000 3d73 3d70 3b31 7865 6365 6922 2066 2573 0000010 2a70 2573 2d7e 707e 703a 6972 746e 7060 0000020 2b60 2b2c 7060 322b 5c60 736e 3d2a 2a70 0000030 3b70 2b70 323d 6e5c 2a22 3939 0a39 000003e so in this case it is 31 because the initial parts are removed.

    Read the article

  • 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

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