logo
down
shadow

I have a program to check if five numbers are prime but it is not working correctly


I have a program to check if five numbers are prime but it is not working correctly

By : Krishan Murari
Date : December 18 2020, 12:00 PM
it helps some times I am trying to create a program that takes in 2 numbers from the user and use a different thread to test each one, this is what i have so far and i know i am a good bit off but i find this threading stuff very difficult ,
I made a few modifications to your code.
code :
import threading 

class PrimeNumber(threading.Thread): 
    def __init__(self, number): 
        threading.Thread.__init__(self) 
        self.Number = number

    def run(self): 
        counter = 2 
        while counter*counter < self.Number: 
            if self.Number % counter == 0: 
                print "%d is not a prime number, because %d = %d * %d" % ( self.Number,      self.Number, counter, self.Number / counter) 
                return 
            counter += 1 
        print "%d is a prime number" % self.Number

threads = [] 
while True: 
    input1 = long(raw_input("Enter first number: ")) 
    if input1 > 1: 
        break 

thread1 = PrimeNumber(input1) 
threads += [thread1] 

while True:
    input2 = long(raw_input("Enter second number: ")) 
    if input2 > 1: 
        break 

thread2 = PrimeNumber(input2) 
threads += [thread2] 


for x in threads:
    x.start()
    x.join()
threads = []
for i in range(5):
    while True: 
        inputNum = long(raw_input("Enter first number: ")) 
        if inputNum > 1: 
            break 

    thread = PrimeNumber(inputNum) 
    threads += [thread] 


Share : facebook icon twitter icon
python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of

python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of


By : Youssef98
Date : March 29 2020, 07:55 AM
should help you out Your error is that you exit the for loop in the first iteration always. You should only exit when you find it has a divisor, but otherwise you should keep looping. When you exit the loop without finding a divisor then is the time to return that fact.
So change:
code :
for x in i: 
    if n % x == 0:
        return print('%s is not prime' % (n))
    else:
        return print('%s is prime number' %(n))
for x in i: 
    if n % x == 0:
        return print('%s is not prime' % (n))
return print('%s is prime number' %(n))
i = [c for c in range(int(math.sqrt(n)),0,-1) if c % 2 != 0]
i = [c for c in range(int(math.sqrt(n)),1,-1) if c % 2 != 0] + [2]
Prime checking program not working on certain numbers

Prime checking program not working on certain numbers


By : brandoncod
Date : March 29 2020, 07:55 AM
may help you . Your code for calculating a prime looks fine. The problem is that you are using the raw strings from the minimum and maximum to create your range. The problem is that strings are compared lexigraphically, so:
code :
"2" < "100" // false
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
var minimum;
var maximum;
var primes;

function myFunction(e) {
  e.preventDefault();
  minimum = Number(document.getElementById('Minimum').value);
  maximum = Number(document.getElementById('Maximum').value);
  primes = [];

  listOfPrimes(minimum, maximum); 
  primes = primes.filter(function(x) {
    return x > 1;
  });
  primes = primes.toString();
  primes = primes.replace(/,(?=[^\s])/g, ", ");
  document.getElementById("Your_Primes").innerHTML = primes;
}

function isPrime(num) {
  for (var i = 2; i <= num / 2; i++)
    if (num % i === 0) {
      return false;
    }
  primes.push(num);
}

function listOfPrimes(min, max) {
  for (var j = min; j <= max; j++) {
    isPrime(j);
  }
}
body {
	background-color: #dbdbdb;
}

#prime-checker {
	background-color: #89a9dd;
	margin: 5px;
	padding: 5px;
	text-align: center;
}

.the-primes {
	background-color: #587cb7;
	padding: 15px;
	margin: 10px;
}
<!doctype html>

<html>
<head>
	<title>Prime Lister</title>
	<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>

<div id="prime-checker">

<form>
  <h2>Minimum Number:</h2><br>
  <input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br> 
  <h2>Maximum Number:</h2><br>
  <input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
  <button id="button" onclick="myFunction(event)">Enter</button>
</form>


<div class="the-primes"><h2>Your Primes:</h2>
  <p id="Your_Primes"></p>
</div>

</div>

<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
function isPrime(num) {
  var max = Math.floor(Math.sqrt(num));
  for (var i = 2; i <= max; i++)
    if (num % i === 0) {
      return false;
    }
  primes.push(num);
}
function isPrimeSqrt(num) {
  var max = Math.floor(Math.sqrt(num));
  for (var i = 2; i <= max; i++)
    if (num % i === 0) {
      return false;
    }
  return true;
}

function isPrimeHalf(num) {
  var max = Math.floor(num / 2);
  for (var i = 2; i <= max; i++)
    if (num % i === 0) {
      return false;
    }
  return true;
}

let now = Date.now();
const pHalf = isPrimeHalf(1010189899);
console.log("Using 'Half' took:", Date.now() - now, "ms. Is prime:", pHalf);
now = Date.now()
const pSqrt = isPrimeSqrt(1010189899);
console.log("Using 'Sqrt' took:", Date.now() - now, "ms. Is prime:", pSqrt);
C++ Program to Display Numbers Between Two Intervals Check Whether a Number can be Express as Sum of Two Prime Numbers

C++ Program to Display Numbers Between Two Intervals Check Whether a Number can be Express as Sum of Two Prime Numbers


By : Alex
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You have to reset your flag at each loop otherwise once it's set with true value, this condition will never be reached if (flag == false).
code :
for (i = n1 ; i <= n2 ; i++)
{
    flag = false; /* Reset the flag */
    for (j = 2 ; j <= i/2 ; j++ )
    {
        if(checkPrime (j) && checkPrime (i-j))
        {
            cout << "Number " << i << " equal sum of two prime number " << j << " + " << i - j << endl;
            flag = true;
        }                       
    }
    if (flag == false)
    {
        cout << "Number " << i << " can't epress to sum of two prime number " << endl;
    }
}
Program to check whether a number can be expressed as a sum of two prime numbers

Program to check whether a number can be expressed as a sum of two prime numbers


By : dragonmaster
Date : March 29 2020, 07:55 AM
will be helpful for those in need There are two errors in your code:
In your function prime() you don't check x for the value of 2, which would also be a prime number.
code :
for(b=2;b<(a+1)/2;b++);
#include <stdio.h>
#include <stdlib.h>

int prime(int x)
{
    int i;

    if (x == 2)
    {
        return 1;
    }

    for (i = 2; i < x; i++)
    {
        if (x % i == 0)
        {
            return 0;
        }
    }

    return 1;
}

int main()
{
    int read_number;
    int summand1;
    int summand2;
    int count = 0;
    int max;
    char buffer[100];

    printf("Enter Number\n");
    fgets(buffer, sizeof(buffer), stdin);
    read_number = atoi(buffer);

    max = (read_number + 1) / 2;

    for (summand1 = 2; summand1 < max; ++summand1)
    {
        summand2 = read_number - summand1;
        if ((prime(summand1) == 1) && (prime(summand2) == 1))
        {
            printf("%d = %d + %d\n", read_number, summand1, summand2);
            count++;
        }
    }

    if (count == 0)
    {
        printf("%d cannot be expressed as sum of two prime numbers.\n", read_number);
    }

    return 0;
}
How to write a program that shows if a number is prime and can display the prime numbers from 1 to 100 in a file

How to write a program that shows if a number is prime and can display the prime numbers from 1 to 100 in a file


By : Hotel Lock
Date : March 29 2020, 07:55 AM
around this issue Really feel you are over-thinking this. You've done the hard part which was writing the isprime function.
Displaying the numbers is trivial, just write a for loop to go through the numbers and check which are prime, if a specific number is prime then print it to screen.
Related Posts Related Posts :
  • How to parse HTML table with rows contaning both <th> and <td> tags under the <tr> tag?
  • Using recursion with map in python
  • Creating lists with loops in Python
  • Returned answer wrong in pyschool Topic 2: Q 6
  • What are the centroid of k-means clusters with PCA decomposition?
  • How do mongoengine filter field not null?
  • Categorize results based on Model in haystack?
  • Error installing pycrypto on my mac
  • Can Django ORM has strip field?
  • Python pack / unpack converts to Objective C
  • Python - Selenium Locate elements by href
  • Couldn't iterate over a dictionary context variable in template, despite having all in place, as far as I know?
  • Test if Django ModelForm has instance on customized model
  • Reading excel column 1 into Python dictionary key, column 2 into value
  • AttributeError: 'module' object has no attribute 'timeit' while doing timeit a python function
  • Accessing button using selenium in Python
  • Removing White Spaces in a Python String
  • Sort timestamp in python dictionary
  • How to use Python 2 packages in Python 3 project?
  • retrieve links from web page using python and BeautifulSoup than select 3 link and run it 4 times
  • applying lambda to tz-aware timestamp
  • Having two Generic ListViews on the same page
  • Merging numpy array elements using join() in python
  • pythonic way to parse/split URLs in a pandas dataframe
  • Added iterating over page id in Scrapy, responses in parse method no longer run
  • wanting to add an age gate to my quiz
  • Removing top empty line when writing a text file Python
  • How to use a template html in different folder on Google App Engine python?
  • Access ndarray using list
  • unable to post file+data using python-requests
  • How to test aws lambda functions locally
  • inconsistent plot between matplotlib and seaborn in Python
  • How matplotlib show obvious changes?
  • Project in Python3, reading files, word data
  • Check for specific Item in list without Iteration or find()
  • Unicode encoding when reading from text file
  • Overloaded variables in python for loops?
  • All elements have same value after appending new element
  • Python Threading loop
  • `_pickle.UnpicklingError: the STRING opcode argument must be quoted`
  • Python: How to stop a variable from exceeding a value?
  • python textblob and text classification
  • Django - Context dictionary for attribute inside a class
  • Database is not updated in Celery task with Flask and SQLAlchemy
  • Shapely intersections vs shapely relationships - inexact?
  • How to extract a percentage column from a periodic column and the sum of the column?
  • Zombie ssh process using python subprocess.Popen
  • Python regex to capture a comma-delimited list of items
  • joining string and long in python
  • Value Error in python numpy
  • Check if any character of a string is uppercase Python
  • TensorFlow - why doesn't this sofmax regression learn anything?
  • Python Anaconda Proxy Setup via .condarc file on Windows
  • Creating django objects from emails
  • Get spotify currently playing track
  • Select multiple columns and remove values according to a list
  • Python - How to Subtract a Variable By 1 Every Second?
  • Tkinter unable to alloc 71867 bytes
  • How to add Variable to JSON Python Django
  • CSRF token missing or invalid Django
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co